http

package
v0.19.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 1, 2025 License: MPL-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package http provides a comprehensive set of HTTP request parameter binding utilities for Go applications. It enables automatic extraction and type conversion of request data (query parameters, headers, path parameters, and JSON body) into Go structs using struct field tags and reflection.

Overview

This package offers several binding functions that can extract data from different parts of an HTTP request.

All binding functions support rich type conversion including basic types, pointers, slices, time.Time, time.Duration, and types implementing encoding.TextUnmarshaler.

Basic Usage

The simplest way to bind request data is using the specialized binding functions:

type UserRequest struct {
	ID     int    `json:"id"`
	Name   string `json:"name"`
	Active bool   `json:"active"`
}

func handler(w http.ResponseWriter, r *http.Request) {
	var req UserRequest
	if err := BindQuery(r, &req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	// Use req.ID, req.Name, req.Active...
}

Multi-Source Binding

The Bind function supports extracting data from different request sources based on struct field tags. Use the `http` tag to specify the data source:

type RequestParams struct {
	UserID   string    `json:"user_id" http:"loc=path"`        // From URL path
	Filter   string    `json:"filter" http:"loc=query"`        // From query string
	APIKey   string    `json:"api_key" http:"loc=header"`      // From headers
	PageSize int       `json:"page_size" http:"loc=query"`     // From query string
	Created  time.Time `json:"created" http:"loc=query,time_format=2006-01-02"`
}

func handler(w http.ResponseWriter, r *http.Request) {
	var params RequestParams
	if err := Bind(r, &params); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	// All fields populated from their respective sources
}

Field Name Resolution

Field names are resolved in the following order:

  1. `json` struct tag value (e.g., `json:"user_name"`)
  2. Snake case conversion if FallbackSnakeCase is enabled (e.g., "UserName" -> "user_name")
  3. Lowercase field name (e.g., "UserName" -> "username")

Fields tagged with `json:"-"` are skipped during binding.

Slice and Multiple Value Handling

Slices are populated from multiple parameter values or CSV-formatted single values:

type FilterRequest struct {
	Tags []string `json:"tags"`  // Multiple ?tags=foo&tags=bar or single ?tags=foo,bar
	IDs  []int    `json:"ids"`   // Multiple ?ids=1&ids=2 or single ?ids=1,2,3
}

CSV parsing is controlled by BindOptions.

TextUnmarshaler Support

Types implementing encoding.TextUnmarshaler can be bound directly:

type Status int

func (s *Status) UnmarshalText(data []byte) error {
	switch string(data) {
	case "active":
		*s = 1
	case "inactive":
		*s = 0
	default:
		return fmt.Errorf("invalid status: %s", data)
	}
	return nil
}

type UserRequest struct {
	Status Status `json:"status"`
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bind

func Bind(r *http.Request, target interface{}) error

Bind extracts and binds HTTP request parameters to a struct based on struct field tags. It supports binding from multiple sources (path, query, headers) based on the `http` struct tag.

Struct fields must have an `http` tag with a location specifier:

  • `http:"loc=path"` - extract from URL path parameters
  • `http:"loc=query"` - extract from query string parameters
  • `http:"loc=header"` - extract from HTTP headers

Field names are resolved from the `json` tag, or fall back to the struct field name.

Example usage:

type RequestParams struct {
    UserID string `json:"user_id" http:"loc=path"`
    Filter string `json:"filter" http:"loc=query"`
    Token  string `json:"token" http:"loc=header"`
}

var params RequestParams
err := Bind(r, &params)

func BindBody

func BindBody(r *http.Request, target interface{}, options ...BindBodyOptions) error

BindBody decodes a JSON request body into a target struct. It supports optional limits on body size and strict field validation.

func BindHeader

func BindHeader(r *http.Request, target interface{}, opts ...*BindOptions) error

BindHeader extracts HTTP headers and binds them to a struct. Header names are case-insensitive as per HTTP specification.

func BindPath

func BindPath(r *http.Request, target interface{}, opts ...*BindOptions) error

BindPath extracts URL path parameters and binds them to a struct.

func BindQuery

func BindQuery(r *http.Request, target interface{}, opts ...*BindOptions) error

BindQuery extracts query string parameters and binds them to a struct. It supports multiple values for the same parameter name, which will be bound to slice fields.

func Problem

func Problem(ctx context.Context, w http.ResponseWriter, err error, options ...ProblemOptions)

Problem outputs an HTTP error response for a handler. It automatically determines the appropriate HTTP status code based on the error type, sets the content type to JSON, and writes the error message as the response body.

func StdPathGetter

func StdPathGetter(r *http.Request, name string) (string, bool)

StdPathGetter uses net/http's PathValue (Go 1.22+) to parse endpoint path parameters.

func Success

func Success(ctx context.Context, w http.ResponseWriter, data interface{}, options ...SuccessOptions)

Success outputs an HTTP success response for a handler. It automatically handles JSON encoding of the response data, sets appropriate content types and headers, and manages different scenarios for nil vs. non-nil data.

When data is nil, it returns a 204 No Content response with no body. When data is provided, it JSON-encodes the data and returns it with a 200 OK status.

Types

type BindBodyOptions

type BindBodyOptions struct {
	// MaxBytes limits the size of the request body (0 = unlimited)
	MaxBytes int64

	// DisallowUnknownFields reject JSON with fields not present in the target
	// struct.
	DisallowUnknownFields bool
}

BindBodyOptions configures the behavior of BindBody.

type BindOptions

type BindOptions struct {
	// PathGetter specifies how to extract path parameters from requests. Only
	// used for BindPath.
	PathGetter PathGetter

	// FallbackSnakeCase controls field name resolution when no explicit tag is
	// present. If true, convert field names to snake_case. If false, it uses
	// lower-case field names.
	FallbackSnakeCase bool

	// SplitSingleCSV enables automatic splitting of comma-separated values in
	// single parameters. When true, a parameter value "a,b,c" will be split
	// into ["a", "b", "c"] for slice fields. Only applies when a single value
	// is received that contains the CSV separator.
	SplitSingleCSV bool

	// CSVSeparator specifies the character used to split CSV values. Only used
	// when SplitSingleCSV is true. Defaults to comma (',').
	CSVSeparator rune

	// DefaultTimeLayout specifies the time format for parsing time.Time fields.
	// Can be overridden per-field using `http:"time_format=..."` struct tags.
	// It defaults to time.RFC3339.
	DefaultTimeLayout string

	// EnableTextUnmarshaler enables support for types implementing
	// encoding.TextUnmarshaler. Default is true.
	EnableTextUnmarshaler bool
}

BindOptions configures the behavior of parameter binding operations. It provides control over naming conventions, data parsing, and type conversion.

type PathGetter

type PathGetter func(r *http.Request, name string) (string, bool)

PathGetter defines a function type for extracting path parameters from HTTP requests. Implementations should return the parameter value and a boolean indicating if the parameter exists.

type ProblemOptions

type ProblemOptions struct {
	// HTTPStatusCode specifies the HTTP status code to return. If zero, the
	// status code will be determined automatically based on the error type.
	HTTPStatusCode int

	// Logger is used for logging errors that occur during response writing. If
	// nil, errors will be logged using the standard log package.
	Logger logger_api.LoggerAPI

	// Headers contains additional HTTP headers to include in the response.
	Headers map[string]string

	// Output is a custom function for handling error output. If provided, this
	// function will be called instead of the default error handling.
	Output func(ctx context.Context, w http.ResponseWriter, err error, code int)
}

ProblemOptions configures how error responses are handled and output.

type SuccessOptions

type SuccessOptions struct {
	// HTTPStatusCode specifies the HTTP status code to return. If zero, defaults
	// to 200 OK for responses with data, or 204 No Content for nil data.
	HTTPStatusCode int

	// Logger is used for logging errors that occur during response writing. If
	// nil, errors will be logged using the standard log package.
	Logger logger_api.LoggerAPI

	// Headers contains additional HTTP headers to include in the response.
	Headers map[string]string

	// Output is a custom function for handling success output. If provided, this
	// function will be called instead of the default success handling.
	Output func(ctx context.Context, w http.ResponseWriter, data interface{}, code int)
}

SuccessOptions configures how success responses are handled and output.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL