-4

I need to send struct data with byte slice data type during socket communication.

type A struct {
    header []byte
    body   []byte
}

So I wrote the following source code to convert the structure to bytes.

var a A
a.header = byte slice data...
a.body   = byte slice data...
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, a)

However, I get an error with the binary.Write function showing the following error:

binary.Write: invalid type main.A

I have found that fixed arrays solve the problem. But since the length of the data is constantly changing, I have to use a slice rather than a fixed array.

Is there a way to solve this problem?

ifnotak
  • 4,147
  • 3
  • 22
  • 36
SangGeol
  • 65
  • 8

1 Answers1

0

If you write a variable length of byte slice, the other end would not know how many bytes it needs to read. You have to communicate the length too.

So one way to send a byte slice is to first write the length (number of bytes) using a fixed-size type, e.g. int32 or int64. Then simply write the byte slice.

For example:

var w io.Writer // This represents your connection
var a A

if err := binary.Write(w, binary.LittleEndian, int32(len(a.header))); err != nil {
    // Handle error
}
if _, err := w.Write(a.header); err != nil {
    // Handle error
}

You may use the same logic to send a.body too.

On the other end, this is how you could read it:

var r io.Reader // This represents your connection
var a A

var size int32
if err := binary.Read(r, binary.LittleEndian, &size); err != nil {
    // Handle error
}
a.header = make([]byte, size)
if _, err := io.ReadFull(r, a.header); err != nil {
    // Handle error
}

Try a working example on the Go Playground.

If you have to transfer more complex structs, consider using the encoding/gob which handles sending slices with ease. For an example and some insights, see Efficient Go serialization of struct to disk.

icza
  • 389,944
  • 63
  • 907
  • 827