How to encode and decode data using a custom binary format in Go?

To encode and decode data using a custom binary format in Go, you can use the encoding/binary package. Here is an example of how to encode and decode data using a custom binary format:

  1. Define the struct representing your data:
type MyData struct { ID uint32 Name string Active bool }
  1. Implement the Encoding and Decoding functions for your struct:
func (d *MyData) Encode() ([]byte, error) { buf := new(bytes.Buffer) // Write ID err := binary.Write(buf, binary.LittleEndian, d.ID) if err != nil { return nil, err } // Write Name err = binary.Write(buf, binary.LittleEndian, uint32(len(d.Name))) if err != nil { return nil, err } _, err = buf.WriteString(d.Name) if err != nil { return nil, err } // Write Active err = binary.Write(buf, binary.LittleEndian, d.Active) if err != nil { return nil, err } return buf.Bytes(), nil } func (d *MyData) Decode(data []byte) error { buf := bytes.NewBuffer(data) // Read ID err := binary.Read(buf, binary.LittleEndian, &d.ID) if err != nil { return err } // Read Name var nameLen uint32 err = binary.Read(buf, binary.LittleEndian, &nameLen) if err != nil { return err } nameBytes := make([]byte, nameLen) _, err = buf.Read(nameBytes) if err != nil { return err } d.Name = string(nameBytes) // Read Active err = binary.Read(buf, binary.LittleEndian, &d.Active) if err != nil { return err } return nil }
  1. Now you can encode and decode your data:
data := MyData{ ID: 42, Name: "John Doe", Active: true, } // Encode data encoded, err := data.Encode() if err != nil { log.Fatal(err) } // Decode data decoded := MyData{} err = decoded.Decode(encoded) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", decoded)

This example demonstrates a custom binary format where we encode the ID as a little-endian 32-bit unsigned integer, the Name as a 32-bit unsigned integer specifying the length followed by the Name string itself, and the Active field as a boolean value.