skip to content
Alvin Lucillo

Encoding data using json and binary pkgs

/ 1 min read

Suppose we have an Event struct

type Event struct {
	ID      uint64 `json:"id"`
	Message string `json:"message"`
}

Encoding/serialization with json.Marshal is straightforward; it serializes the struct into byte. In contrast, EncodeBinary performs manual binary serialization where the position/order is decided.

func EncodeJSON(event Event) ([]byte, error) {
	return json.Marshal(event)
}

func EncodeBinary(event Event) []byte {
	data := make([]byte, 8+len(event.Message))
	binary.BigEndian.PutUint64(data[:8], event.ID)
	copy(data[8:], event.Message)
	return data
}