go - golang casting byte array to struct -


i looking clean way cast byte array struct client-server application. know ppl turn gob package solution not control encoding application. being said, programmed server application not client, there mutual contract protocol being exchanged.

the best come out following.

type t struct {     int16     b int8     c []byte }  func main() {     // create struct , write it.     t := t{a: 99, b: 10}     buf := &bytes.buffer{}      buf1 := []byte{5, 100, 100}     fmt.println(buf1)      buf.write(buf1)      //err := binary.write(buf, binary.bigendian, t)      //if err != nil {     //  panic(err)     //}     fmt.println(buf)      // read empty struct.     t = t{}     err := binary.read(buf, binary.bigendian, &t)     if err != nil {         panic(err)     }     fmt.printf("%d %d", t.a, t.b) } 

however, number bytes not coincide size of struct, go send panic. how can modify work without panic if undersize or oversize

go playground

given using private protocol. it's idea implement own protocol. there many examples of how this.

you limited implementing of encoder. i'd recommend looking @ json.decoder handling buffers rather looking @ straight byte slices. these operate on buffers , useful large data streams.


Comments