Skip to content
Go: Choose a JSON payload type after reading its envelope

Go: Choose a JSON payload type after reading its envelope

November 14, 2026

A message envelope can identify how its payload should be decoded. json.RawMessage keeps the payload as JSON bytes while the program checks the message kind, avoiding an intermediate map of loosely typed values.

Set up

Tested on Linux amd64 with Go 1.26.10. Use Bash with Go on your PATH, a text editor, and the mktemp, rm, and rmdir utilities. The example uses only the standard library. Keep the same terminal through cleanup, and stop if setup fails before saving the source.

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save as go-json-rawmessage-dispatch.go:

package main

import (
	"encoding/json"
	"fmt"
)

func countMessage(input string) (int, error) {
	var envelope struct {
		Kind    string          `json:"kind"`
		Payload json.RawMessage `json:"payload"`
	}
	if err := json.Unmarshal([]byte(input), &envelope); err != nil {
		return 0, fmt.Errorf("invalid envelope")
	}
	if envelope.Kind != "count" {
		return 0, fmt.Errorf("unsupported kind")
	}
	var count *int
	if err := json.Unmarshal(envelope.Payload, &count); err != nil {
		return 0, fmt.Errorf("payload must be an integer")
	}
	if count == nil || *count < 0 {
		return 0, fmt.Errorf("payload must be nonnegative and non-null")
	}
	return *count, nil
}

func main() {
	cases := []struct {
		input string
		valid bool
	}{
		{`{"kind":"count","payload":3}`, true},
		{`{"kind":"count","payload":0}`, true},
		{`{"kind":"other","payload":3}`, false},
		{`{"kind":"count","payload":"3"}`, false},
		{`{"kind":"count","payload":null}`, false},
		{`{"kind":"count"}`, false},
		{`{"kind":"count","payload":-1}`, false},
	}
	for _, c := range cases {
		value, err := countMessage(c.input)
		if (err == nil) != c.valid {
			panic("unexpected acceptance")
		}
		fmt.Printf("%s: value=%d error=%v\n", c.input, value, err)
	}
}

Run:

go run go-json-rawmessage-dispatch.go

Observed output:

{"kind":"count","payload":3}: value=3 error=<nil>
{"kind":"count","payload":0}: value=0 error=<nil>
{"kind":"other","payload":3}: value=0 error=unsupported kind
{"kind":"count","payload":"3"}: value=0 error=payload must be an integer
{"kind":"count","payload":null}: value=0 error=payload must be nonnegative and non-null
{"kind":"count"}: value=0 error=payload must be an integer
{"kind":"count","payload":-1}: value=0 error=payload must be nonnegative and non-null

Read the result

The outer decode checks JSON syntax and reads the kind before the second decode selects an integer payload. A pointer distinguishes JSON null from the valid integer zero. Missing payload bytes fail the second decode, and the application rejects negative counts.

The raw value delays interpretation, not syntax validation of the envelope. Returning zero with an error is not a successful count; callers must check the error before using the numeric result.

Apply it carefully

This is a dispatch example, not a complete strict-JSON policy. Default decoding ignores unknown struct fields, matches field names without regard to case, and accepts duplicate object keys using its normal replacement or merge behavior. Add separate checks if the protocol forbids those forms. The integer range depends on the target architecture. Bound the input before loading it, and choose an explicit wire-level numeric range for a real protocol. The example emits stable application errors rather than exposing decoder internals.

See the Go standard-library reference.

Clean up

Remove the saved source and the empty scratch directory. Go manages its build cache separately. If the directory is not empty, inspect its contents before removing anything else.

rm -- go-json-rawmessage-dispatch.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

Acknowledgements

This post was created with assistance from AI.

Last updated on