Golang:处理二进制数据

I have application client(javascript)-server(golang) and the connection between them are all over websocket. I'm planing using binary messages and i want to create my own protocol for messaging like in this page protocol.

I'm already figure it out in javascript by using DataView but not in golang. Event the primitive data type are similar like they have int8, uint8, int16, uint16 etc, i can't figure it out.

This is the message frame:

1      Uint8      opcode
2      Uint16     msg

This is the example of javascript code handling the incoming message form websocket with message frame above:

websocket.onmessage = function(evt) {
    var data = new DataView(evt.data);
    var opcode = data.getUint8(0);
    var msg = data.getUint16(1);
}

Can you show me how to do it in golang? i'm using gorilla websocket. I know that read message are in []byte, but i don't know how to slice it like javascript does with DataView.

Thanks

For the uint16 you'll need the binary package. Double-check if LittleEndian is what you want.

package main

import (
    "encoding/binary"
)

func main() {
    a := []byte("yak")

    /* opcode  */ _ = uint8(a[0])
    /* message */ _ = binary.LittleEndian.Uint16(a[1:3])
}

https://play.golang.org/p/HRu7C5h2a5