By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Once a client depends on your JSON, its shape is an interface you have to keep. Field names, nesting, nullability and error format are all part of the contract. Evolve additively: add optional fields, never rename or remove one in place, and put breaking changes behind a new version. Relay uses /v1 for that reason and a single error envelope, so clients parse failures the same way they parse successes.
Use struct tags to make the wire contract explicit. json:"-" keeps internal fields out of the payload; omitempty removes zero values but makes 'absent' and 'zero' indistinguishable, so do not use it on fields where that distinction matters. Decode with Decoder.DisallowUnknownFields at the boundary and reject trailing values deliberately.
json.Decoder reads one JSON value at a time from an io.Reader, so it handles newline-delimited JSON of any size with constant memory. json.Unmarshal needs the whole payload in memory and is fine for small bodies only. On the response side, json.Encoder writes directly to the http.ResponseWriter; call it after setting the status code but be aware that a mid-stream encoding error can no longer change the status.
package main
import (
"encoding/json"
"fmt"
"io"
"strings"
)
type event struct {
ID string `json:"id"`
Service string `json:"service"`
Status int `json:"status,omitempty"`
Note string `json:"-"`
}
func main() {
payload := event{ID: "evt-1", Service: "api", Status: 200, Note: "internal"}
encoded, err := json.Marshal(payload)
if err != nil {
panic(err)
}
fmt.Println(string(encoded))
var decoded event
strict := json.NewDecoder(strings.NewReader(`{"id":"evt-2","service":"worker","unknown":true}`))
strict.DisallowUnknownFields()
err = strict.Decode(&decoded)
fmt.Println("strict decode:", err != nil)
stream := `{"id":"evt-3","service":"api","status":201}
{"id":"evt-4","service":"worker","status":500}`
decoder := json.NewDecoder(strings.NewReader(stream))
for {
var next event
if err := decoder.Decode(&next); err == io.EOF {
break
} else if err != nil {
fmt.Println("stream error:", err)
break
}
fmt.Println("streamed", next.ID, next.Service, next.Status)
}
errorBody, err := json.Marshal(map[string]string{"error": "service is required"})
fmt.Println(string(errorBody), err == nil)
}| Contract rule | Do | Do not |
|---|---|---|
| Field names | Pick snake_case and freeze it | Rename a field in place |
| New data | Add optional fields | Change a field's type |
| Zero values | Use pointers or explicit presence when absence matters | Rely on omitempty for semantics |
| Errors | One envelope with a stable code and message | Return bare strings |
| Unknown input | Reject with 400 at the boundary | Silently ignore typos |
| Large payloads | Stream with json.Decoder | Read everything into memory |
Key takeaways
Treat JSON field names and shapes as a versioned contract and evolve additively.
Control the wire format with struct tags; keep internal fields out with json:"-".
Decode strictly at the boundary and decide explicitly about trailing data.
Stream with json.Decoder/json.Encoder for large or newline-delimited payloads.
Use a single error envelope and avoid omitempty where absence and zero must differ.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.