Gopherjs: How can I convert []byte to ArrayBuffer

Created on 26 Jan 2015  路  4Comments  路  Source: gopherjs/gopherjs

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.

All 4 comments

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)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

linkerlin picture linkerlin  路  3Comments

benechols-wf picture benechols-wf  路  6Comments

myitcv picture myitcv  路  6Comments

nytehauq picture nytehauq  路  7Comments

Jimmy99 picture Jimmy99  路  5Comments