I am looking for clean way to cast byte array to struct for client-server application. I know most ppl turn to gob package for this solution however I do not control the encoding for the application. that being said, I only programmed the server application not the client, there is a mutual contract for the protocol that is being exchanged.
The best I could come out is the following.
type T struct {
A int16
B int8
C []byte
}
func main() {
// Create a struct and 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 into an 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, as soon as number bytes does not coincide with the size of the struct, then go will send a panic. How can I modify this to work without the panic if undersize or oversize
<kbd>Go playground</kbd>