Binding
Map JSON, form, multipart, and query data into Go structs.
Binding
Ply binds request data into a struct with Bind, or with a specific source
method when you need control.
type CreateUser struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
app.Post("/users", func(c *core.Context) {
var input CreateUser
if err := c.BindJSON(&input); err != nil {
c.JSON(400, map[string]string{"error": err.Error()})
return
}
c.JSON(201, input)
})Automatic source selection
c.Bind(&input) chooses a source from the request content type:
| Content type | Method used |
|---|---|
application/json | BindJSON |
application/x-www-form-urlencoded | BindForm |
multipart/form-data | BindForm |
| anything else | BindQuery |
Bind also runs validation. The individual bind methods do not.
var input CreateUser
if err := c.Bind(&input); err != nil {
c.JSON(400, map[string]string{"error": err.Error()})
return
}Explicit methods
c.BindJSON(&input)
c.BindQuery(&input)
c.BindForm(&input)BindForm reads multipart values first, then falls back to URL-encoded form
values.
Struct tags
Field names use the first available tag in this order:
queryformjson
If none is present, the Go field name is used. A tag value of - skips the
field.
type Search struct {
Term string `query:"q" json:"q"`
Page int `query:"page" json:"page"`
Tags []string `query:"tag" json:"tag"`
Token string `json:"-" query:"-"`
}Only exported fields are bound. Embedded structs are processed recursively.
Supported field types
- strings
- booleans
- signed and unsigned integers
- floats
- pointers to supported types
- slices of strings or slices of supported scalar types
A query or form value with the same key repeated populates a slice. For other slices, each value is parsed as one element.
Errors
Binding returns an error when:
- the target is not a non-nil struct pointer,
- a value cannot be parsed, or
- a field type is unsupported.
The error includes the field name, for example
field "Age": strconv.ParseInt: parsing "abc": invalid syntax.
BindJSON returns the JSON decoder error directly. It does not reject unknown
fields.
Limits
Binding does not enforce a maximum request size. Configure a body limit at the server or proxy when request bodies are untrusted.

Ply