Skip to main content

Binder

type Binder

type Binder interface {
Bind(c Context, i any) error
}

Data binding interface for client request submission.

In theory, through our implementation of this interface, we can parse data from the following data sources and bind it to our defined struct instances:

  • Path parameters
  • Query parameters
  • Request headers
  • Request body (e.g., JSON, XML, Form, Protobuf, Msgpack, etc.)
  • Cookies
  • Session
  • JWT

Or any other data that can be obtained through the request.

type BindUnmarshaler

type BindUnmarshaler interface {
// UnmarshalParam decodes and assigns a value from form or query parameters.
UnmarshalParam(param string) error
}

BindUnmarshaler is the interface used to wrap the UnmarshalParam method. Types that do not implement this interface but implement encoding.TextUnmarshaler will use that interface.

type DefaultBinder

type DefaultBinder struct{}

Default implementation of the Binder interface, capable of binding path parameters, query parameters, request headers, and request body.

func (*DefaultBinder) BindHeaders

func (*DefaultBinder) BindHeaders(c Context, i any) error

Binds HTTP headers to parameter i.

func (*DefaultBinder) Bind

func (*DefaultBinder) Bind(c Context, i any) (err error)

Implements the Binder interface mentioned earlier, binding submitted data to parameter i in the following order:

  1. Path parameters;
  2. Query parameters;
  3. Request body.

Each step can override the binding values from the previous step.

If we only need to bind from a single source, we can use their own methods BindPathParams, BindQueryParams, BindBody.

func BindPathParams

func BindPathParams(c Context, i any) error

Binds path parameters defined through routing to parameter i.

func BindQueryParams

func BindQueryParams(c Context, i any) error

Binds HTTP request query parameters to parameter i.

func BindBody

func BindBody(c Context, i any) (err error)

Binds data from the HTTP request body to parameter i.

tip

Form Binding - Note that this implementation uses Go's standard library to parse forms. If the content type is not MIMEMultipartForm, form data will be parsed from both URL and BODY.