read-json-optional

command
v14.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: BSD-3-Clause Imports: 2 Imported by: 0

Documentation

Overview

An optional JSON request body with ctx.BindJSONOptional[T].

BindJSONOptional behaves like ctx.BindJSON except that an EMPTY body is a success: it returns the zero value of T with true and skips validation. That makes it the right reader for a filter object the client may omit. A body that is present but malformed still gets the usual 400.

Learn: accept a request whose JSON body may be missing, and still answer 400 when a body is there but malformed. Before: ../read-json-validate

Run:

go run main.go

Try:

curl -i -X POST http://localhost:8080/reports/search                    # 200, no body: every report
curl -i -X POST http://localhost:8080/reports/search \
  -H 'Content-Type: application/json' -d '{"status":"open","min_amount":100}'   # 200, the two matching reports
curl -i -X POST http://localhost:8080/reports/search \
  -H 'Content-Type: application/json' -d '{"status":}'                 # 400 INVALID_ARGUMENT, "malformed JSON"

Next: ../raw-body

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL