Request Data Binding

Learn how to bind HTTP request data to Go structs with type safety and performance

High-performance request data binding for Go web applications. Maps values from various sources (query parameters, form data, JSON bodies, headers, cookies, path parameters) into Go structs using struct tags.

Features

  • Multiple Sources - Query, path, form, header, cookie, JSON, XML, YAML, TOML, MessagePack, Protocol Buffers
  • Type Safe - Generic API for compile-time type safety
  • Zero Allocation - Struct reflection info cached for performance
  • Flexible - Nested structs, slices, maps, pointers, custom types
  • Error Context - Detailed field-level error information
  • Extensible - Custom type converters and value getters

Note: For validation (required fields, enum constraints, etc.), use the rivaas.dev/validation package separately after binding.

Quick Start

JSON Binding

import "rivaas.dev/binding"

type CreateUserRequest struct {
    Name  string `json:"name"`
    Email string `json:"email"`
    Age   int    `json:"age"`
}

// Generic API (preferred)
user, err := binding.JSON[CreateUserRequest](body)
if err != nil {
    // Handle error
}

Query Parameters

type ListParams struct {
    Page   int      `query:"page" default:"1"`
    Limit  int      `query:"limit" default:"20"`
    Tags   []string `query:"tags"`
    SortBy string   `query:"sort_by"`
}

params, err := binding.Query[ListParams](r.URL.Query())

Multi-Source Binding

Combine data from multiple sources:

type CreateOrderRequest struct {
    // From path parameters
    UserID int `path:"user_id"`
    
    // From query string
    Coupon string `query:"coupon"`
    
    // From headers
    Auth string `header:"Authorization"`
    
    // From JSON body
    Items []OrderItem `json:"items"`
    Total float64     `json:"total"`
}

req, err := binding.Bind[CreateOrderRequest](
    binding.FromPath(pathParams),
    binding.FromQuery(r.URL.Query()),
    binding.FromHeader(r.Header),
    binding.FromJSON(body),
)

Learning Path

Follow these guides to master request data binding with Rivaas:

  1. Installation - Get started with the binding package
  2. Basic Usage - Learn the fundamentals of binding data
  3. Query Parameters - Work with URL query strings
  4. JSON Binding - Handle JSON request bodies
  5. Multi-Source - Combine data from multiple sources
  6. Struct Tags - Master struct tag syntax and options
  7. Type Support - Built-in and custom type conversion
  8. Error Handling - Handle binding errors gracefully
  9. Advanced Usage - Custom getters, streaming, and more
  10. Examples - Real-world integration patterns

Supported Sources

SourceFunctionDescription
QueryQuery[T]()URL query parameters (?name=value)
PathPath[T]()URL path parameters (/users/:id)
FormForm[T]()Form data (application/x-www-form-urlencoded)
HeaderHeader[T]()HTTP headers
CookieCookie[T]()HTTP cookies
JSONJSON[T]()JSON body
XMLXML[T]()XML body
YAMLyaml.YAML[T]()YAML body (sub-package)
TOMLtoml.TOML[T]()TOML body (sub-package)
MessagePackmsgpack.MsgPack[T]()MessagePack body (sub-package)
Protocol Buffersproto.Proto[T]()Protobuf body (sub-package)

Why Generic API?

The binding package uses Go generics for compile-time type safety:

// Generic API (preferred) - Type-safe at compile time
user, err := binding.JSON[CreateUserRequest](body)

// Non-generic API - When type comes from variable
var user CreateUserRequest
err := binding.JSONTo(body, &user)

Benefits:

  • ✅ Compile-time type checking
  • ✅ No reflection overhead for type instantiation
  • ✅ Better IDE autocomplete
  • ✅ Cleaner, more readable code

Performance

  • First binding of a type: ~500ns overhead for reflection
  • Subsequent bindings: ~50ns overhead (cache lookup)
  • Query/Path/Form: Zero allocations for primitive types
  • Struct reflection info cached automatically

Next Steps

For integration with rivaas/app, the Context provides a convenient Bind() method that handles all the complexity automatically.


Installation

Install and set up the Rivaas binding package for your Go application

Basic Usage

Learn the fundamentals of binding request data to Go structs

Query Parameters

Master URL query string binding with slices, defaults, and type conversion

JSON Binding

Bind and parse JSON request bodies with automatic type conversion and validation

Multi-Source Binding

Combine multiple data sources with precedence rules for flexible request handling

Struct Tags

Master struct tag syntax for precise control over data binding

Type Support

Complete reference for all supported data types and conversions

Error Handling

Master error handling patterns for robust request validation and debugging

Advanced Usage

Advanced techniques including custom converters, binders, and extension patterns

Examples

Real-world examples and integration patterns for common use cases