Documentation
¶
Overview ¶
Reading and validating a JSON body with ctx.BindJSON[T].
A payload type that implements Validate() error (the iris.Validatable interface) is validated automatically after decoding: ctx.BindJSON writes the 400 response itself and returns false, so the handler only ever sees decoded, valid input. The rest/errors/validation builders (String, Number, Join) produce one entry per failed field; Join drops the fields that passed and returns nil when everything did.
Learn: decode and validate a JSON body in one call and know the exact 400 clients receive. Before: ../query-and-forms
Run:
go run main.go
Try:
curl -i -X POST http://localhost:8080/users -H 'Content-Type: application/json' \
-d '{"name":"Gerasimos Maropoulos","email":"kataras2006@hotmail.com","age":36}' # 201, the payload echoed
curl -i -X POST http://localhost:8080/users -H 'Content-Type: application/json' \
-d '{"name":"","email":"nope","age":0}' # 400, one entry per field
The 400 body, where "id" is a per-error tracking id:
{
"id": "2dd92ea9-1058-4874-b096-c80269a826a0",
"http_error_code": {"canonical_name":"INVALID_ARGUMENT","status":400},
"message": "validation failure",
"detail": "fields were invalid",
"validation": [
{"field":"name","value":"","reason":"must not be empty, must be between 2 and 100 characters"},
{"field":"email","value":"nope","reason":"must be a valid email address"},
{"field":"age","value":0,"reason":"must be positive"}
]
}
Next: ../read-json-optional
Click to show internal directories.
Click to hide internal directories.