skip to content
Alvin Lucillo

Decoding data using json and binary pkgs

/ 1 min read

Today’s entry is related to yesterday’s; they’re just a reverse. It is evident that manual binary deserialization (and serialization) is not scalable over time. But there are factors worth considering which future daily entries will discuss.

func DecodeJSON(data []byte) (Event, error) {
	var event Event
	err := json.Unmarshal(data, &event)
	return event, err
}

func DecodeBinary(data []byte) (Event, error) {
	if len(data) < 8 {
		return Event{}, errors.New("binary event is shorter than its 8-byte ID")
	}

	return Event{
		ID:      binary.BigEndian.Uint64(data[:8]),
		Message: string(data[8:]),
	}, nil
}