Copper provides chttp.JSONReaderWriter to read, validate, and write JSON. Add it to your router’s params and wire will inject it for you:
copper scaffold:router generates a router with only a Logger. Add the RW field yourself when your router serves JSON.
Reading JSON
ReadJSON decodes the request body into a struct. If the body is empty, malformed, or fails validation, the 400 Bad Request response will automatically be written for you and ReadJSON returns false, so your handler only needs to return:
Validating
ReadJSON validates the body with govalidator valid: tags before your handler sees it:
For your own domain types, you may register a custom validator once and use it like any other tag:
Of course, some rules span multiple fields and don’t fit in tags. You may check these at the top of your handler and respond early:
Writing JSON
WriteJSON marshals your data and sets the Content-Type header. The status code defaults to 200 OK:
If Data is an error, it will be encoded as {"error": "<message>"}, which is convenient for 4xx responses.
For a bare 401, you may use the Unauthorized shorthand:
Putting It Together
Let’s put it all together in a complete handler that reads and validates the body, calls the service, maps known errors to status codes, and responds:
Sentinel errors like ErrRocketNotFound are declared in the service package with errors.New. To learn more, see Error Handling.