Skip to content

Binding

HTTP request binding system that automatically maps HTTP request data to Go structs using struct tags.

Supported Struct Tags

Own struct types can implement the encoding.TextUnmarshaler interface for custom parsing logic.

TagDescriptionExample
json:"field_name"Binds from JSON request bodyjson:"username"
xml:"field_name"Binds from XML request bodyxml:"title"
form:"field_name"Binds from form dataform:"first_name"
query:"param_name"Binds from URL query parametersquery:"page"
header:"Header-Name"Binds from HTTP headersheader:"User-Agent"
uri:"param_name"Binds from URI path parametersuri:"user_id"
param:"param_name"Alternative to uriparam:"category"
file:"field_name"Binds uploaded filesfile:"avatar"
time_format:"layout"Custom time parsing formattime_format:"2006-01-02"

Supported Data Types

  • Primitives: string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool
  • Slices: []string, []int, []bool, etc.
  • Pointers: *string, *int, etc. (for optional fields)
  • Time: time.Time with customizable parsing format
  • Duration: time.Duration
  • Files: *multipart.FileHeader, []*multipart.FileHeader
  • Nested Structs: Full support for nested struct binding

Basic Usage

go
package main

import (
    "net/http"
    "github.com/rakunlabs/ada/utils/bind"
)

type User struct {
    ID       int    `json:"id"`
    Username string `json:"username" form:"username"`
    Email    string `json:"email" form:"email"`
    Page     int    `query:"page"`
    APIKey   string `header:"X-API-Key"`
}

func handleUser(w http.ResponseWriter, r *http.Request) {
    var user User
    if err := bind.Bind(r, &user); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // user is now populated with data from the request
}

// //////////////////////////////////
// if using the ada.Context function

func handleUser(c *ada.Context) error {
    var user User
    if err := c.Bind(&user); err != nil {
        return c.SetStatus(http.StatusBadRequest).Err(err)
    }

// user is now populated with data from the request
}