Skip to content

Request Binding ​

Added: v1.0.0

Zen provides struct-tag-based binding for request bodies, path parameters, query parameters, and headers. Binding uses reflection with no intermediate caching - each call parses fresh.

JSON ​

Decodes the request body as JSON. Uses json.Decoder for streaming:

go
var req CreateUser
if err := c.BindJSON(&req); err != nil {
    c.Error(400, err.Error())
    return
}

XML ​

Decodes the request body as XML. Uses xml.Decoder for streaming:

go
var req XMLRequest
if err := c.BindXML(&req); err != nil {
    c.Error(400, err.Error())
    return
}

Form ​

Decodes application/x-www-form-urlencoded or multipart/form-data bodies. Uses form struct tags:

go
type LoginForm struct {
    Username string `form:"username"`
    Password string `form:"password"`
}

var form LoginForm
if err := c.BindForm(&form); err != nil {
    c.Error(400, err.Error())
    return
}

Query Parameters ​

Binds URL query parameters to struct fields using query tags. Falls back to json tag if query is absent:

go
type Search struct {
    Query string `query:"q"`
    Page  int    `query:"page"`
}

var q Search
if err := c.BindQueryParams(&q); err != nil {
    c.Error(400, err.Error())
    return
}

Supports repeated query params: ?id=1&id=2 binds as []string{"1", "2"} when the struct field type is []string.

Path Parameters ​

Binds URL path parameters to struct fields using param tags. Falls back to json tag if param is absent:

go
type Params struct {
    ID     string `param:"id"`
    PostID string `param:"postId"`
}

var p Params
if err := c.BindPathValues(&p); err != nil {
    c.Error(400, err.Error())
    return
}

Headers ​

Binds request headers to struct fields using header tags:

go
type Headers struct {
    UserID   string `header:"X-User-Id"`
    APIToken string `header:"X-Api-Token"`
}

var h Headers
if err := c.BindHeaders(&h); err != nil {
    c.Error(400, err.Error())
    return
}

Auto-Detect ​

c.Bind() detects content type and binds body, path parameters, and query parameters in one call. For GET/DELETE/HEAD, it also binds query parameters:

go
c.Bind(&req) // detects content type, binds path/query/body

Supported Field Types ​

Go TypeInput Format
stringraw value
int, int8-int64decimal string
uint, uint8-uint64decimal string
float32, float64decimal string
bool1/t/T/TRUE/true/True, 0/f/F/FALSE/false/False (strconv.ParseBool)
[]stringrepeated params

Released under the MIT License.