I have some js returned ArrayBuffer object, and I want to use golang to process it as []byte. But I don't know how to do it. I did not find the document about it.
I'm sorry, I got it jsobject.Interface().([]byte)
Sorry again, I have problem about convert []byte to ArrayBuffer
My code here:
var chromeSocketsTcp = js.Global.Get("chrome").Get("sockets").Get("tcp")
type ChromeTcpSocket struct {
socketId int
}
func awaitInvokeResult(object js.Object, args ...interface{}) js.Object {
await := make(chan js.Object)
object.Invoke(append(args, func(result js.Object) {
go func() {
await <- result
}()
})...)
return <-await
}
func (self *ChromeTcpSocket) Write(p []byte) (int, error) {
sendInfo := awaitInvokeResult(chromeSocketsTcp.Get("send"), self.socketId, p)
code := sendInfo.Get("code").Int()
if code < 0 {
return 0, chromeLastError(code)
}
return sendInfo.Get("bytesSent").Int(), nil
}
I've got runtime error in chrome app context.
Uncaught Error: Invocation of form sockets.tcp.send(integer, object, function) doesn't match definition sockets.tcp.send(integer socketId, binary data, function callback)
I traced in the actual call to chrome.sockets.tcp.send. The second argument is actually just Uint8Array.
but chrome.sockets.tcp.send require an ArrayBuffer.
I've tried sendInfo := awaitInvokeResult(chromeSocketsTcp.Get("send"), self.socketId, js.InternalObject(p).Get("buffer")), but it doesn't work.
solved by this way:
func uint8ArrayToArrayBuffer(p js.Object) js.Object {
buffer := p.Get("buffer")
byteOffset := p.Get("byteOffset").Int()
byteLength := p.Get("byteLength").Int()
if byteOffset != 0 || byteLength != buffer.Get("byteLength").Int() {
return buffer.Call("slice", byteOffset, byteOffset+byteLength)
}
return buffer
}
func byteSliceToArrayBuffer(p []byte) js.Object {
return js.InternalObject(uint8ArrayToArrayBuffer).Invoke(p)
}
I know you found a workaround, but to answer your first question. I find that the most performant way to convert a javascript ArrayBuffer to []byte array in go is...
// buffer is an ArrayBuffer js.Object
bytes := js.Global.Get("Uint8Array").New(buffer).Interface().([]byte)