I'm trying to write a game server and need to create the packet I'll be sending back to the client. I am writing all the data into a bytes.Buffer then I want to prefix the total size of the packet before getting the bytes and sending it to the client.
I was thinking of something like this:
// is it bad to call `var b bytes.Buffer` every time I create a packet?
func CreatePacket() []byte {
var b bytes.Buffer
// size
binary.Write(b, binary.LittleEndian, 0) // insert at end
// body (variable number of writes)
binary.Write(b, binary.LittleEndian, data)
// update the size at offset 0
binary.Write(b, binary.LittleEndian, b.Len())
return b.Bytes()
}
But I can't find any method to seek or modify the offset.
This doesn't work, why?
var packet = b.Bytes()
// the size is really at offset 2. offset 0 is an ID.
binary.LittleEndian.PutUint16(packet, uint16(0xF3))
binary.LittleEndian.PutUint16(packet, uint16(len(packet)))