I have a net/socket open. I need to read a structured protocol off the wire. Ie I have
messagelength|type|value|type|value ...
where messagelength is 4 bytes, type one byte, value depends on type,...
I am trying to work out the no-brainer way of doing this in go. I am swamped by io,bufio,encoding... I cant find the right place to start and cant find samples. Looking for ReadInt32, ReadByte,....
Next thing - i need to assemble a reply -> WriteInt32, WriteString, WriteByte,....
Trying to convert python to go, python code uses struct.unpack / pack
You can use the package encoding/binary. The only functions you will need are Read() and Write(). Here is how you use them:
The Read() function has the following signature:
func Read(r io.Reader, order ByteOrder, data interface{}) error
This function reads from r
in order ByteOrder
into data. data
must be a pointer to a fixed-size value (e.g. an int32
, a byte or a struct with only fixed size members) or a slice of such values. If you pass a pointer to a struct, struct fields are read in without padding, data corresponding for blank fields (i.e. those named _) is read and discarded (ideal for padding).
For your specific problem, declare a struct that matches the header of your data stream.
type Header struct {
Length uint32
Type uint8
}
Consume the header of a packet (assume big endian):
var hdr Header
if err = Read(connection, binary.BigEndian, &hdr); err != nil {
// deal with read error
}
Switch over the type byte:
switch hdr.Type {
// for each type, read into a type-specific struct
// ...
}
Write()
is similar but writes instead of reading.