What We Talk About

Our thoughts on software engineering, product development, and cooperative workplaces.

Safer Binary Decoding in Go

Posted on in Engineering 

Go is a popular language choice for building web services. Typically, when building those web services, we end up encoding/decoding JSON as the data format. The encoding/json package provides a safe way to turn JSON payloads into Go structs, and vice versa.

However, if we need to handle raw []byte that follow a binary encoding format that is not self-describing, we need to do a bit more work and implement the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler directly. Since we're dealing with []byte, we need to respect slice bounds to avoid triggering a panic() and crashing our service.

Let's look at the two ways we can decode data into Go structs and compare how one way will be safer than the other while yielding the same result. As an added bonus, we'll end up with easier to understand code.