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.
Code
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
errbefore 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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.