httpx

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package httpx contains HTTP adapters, middleware, and router helpers used by modules.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccessLog

func AccessLog(cfg config.AccessLogConfig, log *logx.Logger) func(http.Handler) http.Handler

AccessLog emits structured request logs with sampling and slow/error overrides.

Notes: - Always logs 5xx responses - Always logs requests above SlowThreshold - Uses route patterns to keep log cardinality stable

func Adapter

func Adapter[Req any, Resp any](fn HandlerFunc[Req, Resp]) http.Handler

Adapter converts a typed HandlerFunc into a standard http.Handler.

Behavior: - Decodes and validates JSON input for non-NoBody requests - Writes unified response envelope through response package helpers - Uses request-id from context for deterministic error responses

func AssembleGlobalMiddleware

func AssembleGlobalMiddleware(base http.Handler, cfg config.HTTPMiddlewareConfig, log *logx.Logger, tracingSvc *tracing.Service) http.Handler

AssembleGlobalMiddleware wraps a base handler with configured global middleware.

Execution order (outermost -> innermost):

  1. RequestID (if enabled)
  2. ClientIP (trusted proxies optional)
  3. Recoverer (if enabled)
  4. CORS (if enabled)
  5. SecurityHeaders (if enabled)
  6. MaxBodyBytes (if enabled)
  7. RequestTimeout (if enabled)
  8. Tracing (if enabled)
  9. AccessLog (if enabled)

This order keeps request_id available in recover logs, and keeps recoverer around downstream middleware/handlers.

For cache and rate-limit route policy behavior, see docs/cache-guide.md and docs/policies.md.

func Bool

func Bool(v bool) *bool

Bool returns a bool pointer for optional envelope fields. Deprecated: use BoolPtr for clearer intent.

func BoolPtr

func BoolPtr(v bool) *bool

BoolPtr returns a bool pointer for optional envelope fields.

Usage:

return httpx.Result[T]{OK: httpx.BoolPtr(true), Data: value}, nil

func CORS

func CORS(cfg config.CORSConfig) func(http.Handler) http.Handler

CORS applies CORS headers and handles preflight requests.

func CaptureRoutePattern

func CaptureRoutePattern(next http.Handler) http.Handler

CaptureRoutePattern records the resolved chi route pattern on response writer wrappers.

func ClientIP

func ClientIP(cfg config.ClientIPConfig) func(http.Handler) http.Handler

ClientIP resolves the client IP address and stores it in the request context. If TrustedProxies is empty, only r.RemoteAddr is used.

func DecodeAndValidateJSON

func DecodeAndValidateJSON(w http.ResponseWriter, r *http.Request, dst any) error

DecodeAndValidateJSON strictly decodes a JSON request body into dst, applies the default body limit, rejects trailing values, and runs Validate when available.

func MaxBodyBytes

func MaxBodyBytes(limit int64) func(http.Handler) http.Handler

MaxBodyBytes limits request body size for requests that can carry bodies.

func Recoverer

func Recoverer(log *logx.Logger) func(http.Handler) http.Handler

Recoverer returns middleware that catches panics, logs them with structured context, and returns a sanitized 500 response. The logger is injected explicitly — no global state.

func RequestID

func RequestID(next http.Handler) http.Handler

RequestID injects X-Request-Id header and request context value.

Behavior: - Accepts incoming X-Request-Id when format is valid - Generates cryptographically random ID when missing/invalid

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns request id stored by RequestID middleware.

func RequestTimeout

func RequestTimeout(timeout time.Duration) func(http.Handler) http.Handler

RequestTimeout enforces per-request context deadline for downstream handlers.

Behavior: - Disabled when timeout <= 0 - Returns 504 timeout envelope when deadline expires before any response header is written

func RoutePattern

func RoutePattern(r *http.Request, statusCode int, capturedPattern string) string

RoutePattern resolves a stable route label for instrumentation.

func SecurityHeaders

func SecurityHeaders(next http.Handler) http.Handler

SecurityHeaders applies a conservative set of headers suitable for APIs.

func Tracing

func Tracing(svc *tracing.Service) func(http.Handler) http.Handler

Tracing wraps requests in OpenTelemetry server spans when tracing is enabled.

Behavior: - Extracts incoming trace context from headers - Names spans with low-cardinality route patterns - Records status code and request metadata attributes

func URLParam

func URLParam(r *http.Request, key string) string

URLParam returns route parameter value by key.

This helper keeps routing code decoupled from concrete router implementation.

Types

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context wraps http.Request with typed convenience helpers for handlers.

func NewContext

func NewContext(r *http.Request) *Context

NewContext constructs a handler context wrapper from incoming request.

func (*Context) Auth

func (c *Context) Auth() (auth.AuthContext, bool)

Auth returns authenticated principal context if available.

func (*Context) ClientIP

func (c *Context) ClientIP() (string, bool)

ClientIP returns resolved client IP from context when available.

func (*Context) Context

func (c *Context) Context() context.Context

Context returns request context or background context when request is nil.

func (*Context) Header

func (c *Context) Header(name string) string

Header returns trimmed request header value by name.

func (*Context) Param

func (c *Context) Param(name string) string

Param returns trimmed route parameter value by name.

func (*Context) Query

func (c *Context) Query(name string) string

Query returns trimmed query parameter value by name.

func (*Context) Request

func (c *Context) Request() *http.Request

Request returns the underlying HTTP request.

func (*Context) RequestID

func (c *Context) RequestID() string

RequestID returns request id from context.

type HandlerFunc

type HandlerFunc[Req any, Resp any] func(ctx *Context, req Req) (Resp, error)

HandlerFunc is the unified typed handler signature used by Adapter.

type Mux

type Mux struct {
	// contains filtered or unexported fields
}

Mux is the chi-backed Router implementation. It satisfies both Router (for module registration) and http.Handler (for the HTTP server).

func NewMux

func NewMux() *Mux

NewMux creates a production-ready router backed by chi.

func (*Mux) Handle

func (m *Mux) Handle(method string, pattern string, h http.Handler, policies ...policy.Policy)

Handle registers a handler for the given HTTP method and pattern. Chi provides native method routing with automatic 405 Method Not Allowed for known paths reached with the wrong method, and 404 Not Found for unknown paths.

Note: chi's Method() does not return an error at registration time; invalid patterns will panic immediately (fail-fast), which is acceptable for route registration at startup.

func (*Mux) ServeHTTP

func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP delegates to the underlying chi router.

func (*Mux) Use

func (m *Mux) Use(middlewares ...func(http.Handler) http.Handler)

Use attaches global middlewares to the underlying router.

type NoBody

type NoBody struct{}

NoBody marks request handlers that do not accept a JSON request payload.

type Result

type Result[T any] struct {
	// Status sets HTTP status code. Defaults to 200 when zero.
	Status int
	// OK overrides envelope ok flag when set.
	OK *bool
	// Data is the response payload written to envelope data.
	Data T
}

Result allows handlers to control envelope status and OK flag explicitly.

func (Result[T]) HTTPData

func (r Result[T]) HTTPData() any

HTTPData returns response payload for envelope serialization.

func (Result[T]) HTTPOK

func (r Result[T]) HTTPOK() bool

HTTPOK resolves envelope ok flag from explicit value or status code.

func (Result[T]) HTTPStatus

func (r Result[T]) HTTPStatus() int

HTTPStatus resolves default status when Status is not explicitly set.

type Router

type Router interface {
	Handle(method string, pattern string, h http.Handler, policies ...policy.Policy)
	Use(middlewares ...func(http.Handler) http.Handler)
}

Router is the abstraction modules use to register routes. Module code depends only on this interface, never on chi directly.

type Validatable

type Validatable interface {
	Validate() error
}

Validatable is implemented by DTOs that perform semantic validation.

Jump to

Keyboard shortcuts

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