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
Click to show internal directories.
Click to hide internal directories.