binding

command
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Example: request binding + validation, three ways.

All three endpoints accept the same JSON payload and produce the same shape of 400 response. They differ in what they do on success:

POST /users/echo    — server.JSONEcho[CreateUser](). Validates the
                      body and echoes the validated value back. No
                      business logic — useful for webhook acks, dev
                      stubs, and "did this payload pass validation?"
                      endpoints.
POST /users         — server.JSONHandler. Validates, then runs real
                      business logic (here: assigns a server-side ID,
                      lowercases the email) and returns a different
                      response type.
POST /users-manual  — uses the lower-level server.BindJSON and renders
                      the 400 envelope by hand. Useful when you need
                      to add headers, stream, or build a custom shape.

Rule of thumb: if your handler would be `func(_, in) (in, nil)`, reach for JSONEcho. The moment you need to compute, transform, or look anything up, reach for JSONHandler.

Try it:

go run ./examples/binding &
curl -s -X POST localhost:8080/users \
     -H 'Content-Type: application/json' \
     -d '{"name":"Ada","email":"Ada@Example.com","age":36,"role":"admin"}'
curl -s -X POST localhost:8080/users/echo \
     -H 'Content-Type: application/json' \
     -d '{"name":"Ada","email":"ada@example.com","age":36,"role":"admin"}'
curl -s -X POST localhost:8080/users \
     -H 'Content-Type: application/json' \
     -d '{"name":"A","email":"nope","age":12,"role":"superuser"}'

Jump to

Keyboard shortcuts

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