Limit JSON Input With io.LimitReader

Cap untrusted JSON at a byte budget by reading through io.LimitReader with a one-byte probe, rejecting oversized payloads before json.Unmarshal sees them.

GoSecurity Boundaries

Code

gosnippet
43 lines
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"strings"
)

// 入站 JSON 的大小上限;多读 1 字节用于区分“恰好装满”与“超限”
const maxConfigBytes = 64

var ErrPayloadTooLarge = errors.New("payload exceeds limit")

func decodeConfig(r io.Reader) (map[string]string, error) {
	data, err := io.ReadAll(io.LimitReader(r, maxConfigBytes+1))
	if err != nil {
		return nil, err
	}
	if len(data) > maxConfigBytes {
		return nil, ErrPayloadTooLarge
	}
	var cfg map[string]string
	if err := json.Unmarshal(data, &cfg); err != nil {
		return nil, err
	}
	return cfg, nil
}

func main() {
	small := `{"region":"eu-1","tier":"standard"}`
	large := strings.Repeat("a", 200)

	for _, body := range []string{small, large} {
		cfg, err := decodeConfig(strings.NewReader(body))
		if err != nil {
			fmt.Println("blocked:", err)
			continue
		}
		fmt.Println("decoded region:", cfg["region"])
	}
}

How the snippet works

Count the functions decodeConfig and main as the entire surface area of Limit JSON Input With io.LimitReader.

One loop does the cycling here: for _, body := range []string{small, large}. The Go idiom runs throughout — 3 if err != nil checks, each handling the failure on the spot.

What to watch for

  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Applying it

Entry signature: func decodeConfig(r io.Reader) (map[string]string, error)

The file tags its output — blocked:, decoded region: — when the file runs.

The demo flow inside main is decodeConfig — run the file to see it end to end.

Statements that set the outcome here

for _, body := range []string{small, large} {
cfg, err := decodeConfig(strings.NewReader(body))
if err != nil {
fmt.Println("blocked:", err)
continue
}
fmt.Println("decoded region:", cfg["region"])
}
if err != nil {
return nil, err
}
var ErrPayloadTooLarge = errors.New("payload exceeds limit")

Interactive Tools for This Topic

FAQ

How should callers handle failures?
As returned `error` values — 3 sites in the snippet check `err` before using other results.
What does Limit JSON Input With io.LimitReader print when run?
Execute the whole file; each printed line is prefixed with a label like `blocked:`, `decoded region:`.