Documentation
¶
Overview ¶
Package httpx contains HTTP adapters, middleware, and router helpers used by modules.
Index ¶
- func AccessLog(cfg config.AccessLogConfig, log *logx.Logger) func(http.Handler) http.Handler
- func Adapter[Req any, Resp any](fn HandlerFunc[Req, Resp]) http.Handler
- func AssembleGlobalMiddleware(base http.Handler, cfg config.HTTPMiddlewareConfig, log *logx.Logger, ...) http.Handler
- func Bool(v bool) *bool
- func BoolPtr(v bool) *bool
- func CORS(cfg config.CORSConfig) func(http.Handler) http.Handler
- func CaptureRoutePattern(next http.Handler) http.Handler
- func ClientIP(cfg config.ClientIPConfig) func(http.Handler) http.Handler
- func DecodeAndValidateJSON(w http.ResponseWriter, r *http.Request, dst any) error
- func MaxBodyBytes(limit int64) func(http.Handler) http.Handler
- func Recoverer(log *logx.Logger) func(http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- func RequestIDFromContext(ctx context.Context) string
- func RequestTimeout(timeout time.Duration) func(http.Handler) http.Handler
- func RoutePattern(r *http.Request, statusCode int, capturedPattern string) string
- func SecurityHeaders(next http.Handler) http.Handler
- func Tracing(svc *tracing.Service) func(http.Handler) http.Handler
- func URLParam(r *http.Request, key string) string
- type Context
- func (c *Context) Auth() (auth.AuthContext, bool)
- func (c *Context) ClientIP() (string, bool)
- func (c *Context) Context() context.Context
- func (c *Context) Header(name string) string
- func (c *Context) Param(name string) string
- func (c *Context) Query(name string) string
- func (c *Context) Request() *http.Request
- func (c *Context) RequestID() string
- type HandlerFunc
- type Mux
- type NoBody
- type Result
- type Router
- type Validatable
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AccessLog ¶
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):
- RequestID (if enabled)
- ClientIP (trusted proxies optional)
- Recoverer (if enabled)
- CORS (if enabled)
- SecurityHeaders (if enabled)
- MaxBodyBytes (if enabled)
- RequestTimeout (if enabled)
- Tracing (if enabled)
- 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 ¶
Bool returns a bool pointer for optional envelope fields. Deprecated: use BoolPtr for clearer intent.
func BoolPtr ¶
BoolPtr returns a bool pointer for optional envelope fields.
Usage:
return httpx.Result[T]{OK: httpx.BoolPtr(true), Data: value}, nil
func CaptureRoutePattern ¶
CaptureRoutePattern records the resolved chi route pattern on response writer wrappers.
func ClientIP ¶
ClientIP resolves the client IP address and stores it in the request context. If TrustedProxies is empty, only r.RemoteAddr is used.
func DecodeAndValidateJSON ¶
DecodeAndValidateJSON strictly decodes a JSON request body into dst, applies the default body limit, rejects trailing values, and runs Validate when available.
func MaxBodyBytes ¶
MaxBodyBytes limits request body size for requests that can carry bodies.
func Recoverer ¶
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 ¶
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 ¶
RequestIDFromContext returns request id stored by RequestID middleware.
func RequestTimeout ¶
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 ¶
RoutePattern resolves a stable route label for instrumentation.
func SecurityHeaders ¶
SecurityHeaders applies a conservative set of headers suitable for APIs.
Types ¶
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context wraps http.Request with typed convenience helpers for handlers.
func NewContext ¶
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) Context ¶
Context returns request context or background context when request is nil.
type HandlerFunc ¶
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 (*Mux) Handle ¶
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.
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]) HTTPStatus ¶
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.