How do I encode/decode binary protocols in Go?

In Go, encoding and decoding binary protocols can be efficiently handled using the `encoding/binary` package. This package allows you to convert Go values to binary data and vice versa. Below is a simple example showcasing how to encode and decode binary data using this package.

package main import ( "encoding/binary" "fmt" "bytes" ) type ExampleStruct struct { A int32 B int64 } func main() { // Create an instance of ExampleStruct original := ExampleStruct{A: 42, B: 1000} // Create a buffer to hold the binary data buf := new(bytes.Buffer) // Encode the data into binary format err := binary.Write(buf, binary.LittleEndian, original) if err != nil { fmt.Println("Error encoding:", err) return } // Decode the data from binary format var decoded ExampleStruct err = binary.Read(buf, binary.LittleEndian, &decoded) if err != nil { fmt.Println("Error decoding:", err) return } // Output the original and decoded structs fmt.Printf("Original: %+v\n", original) fmt.Printf("Decoded: %+v\n", decoded) }

go encoding decoding binary protocol encoding/binary Go programming