Documentation
¶
Index ¶
- Variables
- func BindJSON(r *http.Request, dst any) error
- func CORS(config CORSConfig) func(http.Handler) http.Handler
- func ContentTypeJson(next http.Handler) http.Handler
- func GetCtx[T any](r *http.Request, key any) (T, bool)
- func Gzip(next http.Handler) http.Handler
- func Handle(handlers []MiddlewareFunc, handler http.Handler) http.Handler
- func JSON(w http.ResponseWriter, code int, data any)
- func MaxBodyBytes(limit int64) func(http.Handler) http.Handler
- func Metrics(recorder *MetricsRecorder) func(http.Handler) http.Handler
- func NewHttp(config ServerConfig) *httpServerImpl
- func NewRouter(config RouterConfig) *routerImpl
- func Params(r *http.Request) map[string]string
- func Query(r *http.Request, key string) string
- func QueryBool(r *http.Request, key string, defaultVal bool) bool
- func QueryFloat(r *http.Request, key string, defaultVal float64) float64
- func QueryInt(r *http.Request, key string, defaultVal int) int
- func RateLimiter(config RateLimiterConfig) func(http.Handler) http.Handler
- func RecoverMiddleware(next http.Handler, stackTrace ...bool) http.Handler
- func RemoteIP(r *http.Request) string
- func RequestID(next http.Handler) http.Handler
- func RequestLogger(next http.Handler, logger ...Logger) http.Handler
- func SetCtx(r *http.Request, key, value any) *http.Request
- func Text(w http.ResponseWriter, code int, msg string)
- func URLParam(r *http.Request, key string) string
- func WriteError(w http.ResponseWriter, code int, msg string)
- type CORSConfig
- type ContextKey
- type HttpRouter
- type HttpServer
- type LogLevel
- type Logger
- type MetricsRecorder
- type MiddlewareFunc
- type Param
- type RateLimiterConfig
- type RouteInfo
- type RouteRegister
- type Router
- type RouterAction
- type RouterConfig
- type ServerConfig
Constants ¶
This section is empty.
Variables ¶
var METHODS = []string{
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"PATCH",
"OPTIONS",
}
METHODS lists all HTTP methods the router supports.
Functions ¶
func BindJSON ¶
BindJSON decodes the request body as JSON into dst. dst must be a pointer. The caller is responsible for translating a non-nil error into an HTTP response (e.g. http.StatusBadRequest, or http.StatusRequestEntityTooLarge if the body was wrapped with MaxBodyBytes).
func CORS ¶
func CORS(config CORSConfig) func(http.Handler) http.Handler
CORS returns a middleware that handles cross-origin requests. Preflight (OPTIONS) requests return 204 without calling the next handler.
func ContentTypeJson ¶
ContentTypeJson sets Content-Type: application/json on every response.
func GetCtx ¶
GetCtx retrieves a typed value from the request context. Returns the zero value and false if the key is missing or the type doesn't match.
func Gzip ¶
Gzip returns a middleware that compresses responses with gzip when the client sends Accept-Encoding: gzip.
func Handle ¶
func Handle(handlers []MiddlewareFunc, handler http.Handler) http.Handler
Handle builds a middleware chain around the given handler. Middleware order: the first middleware in the slice is the outermost wrapper. If handler is nil, a default http.NewServeMux is used as the base.
func JSON ¶
func JSON(w http.ResponseWriter, code int, data any)
JSON writes data as JSON with the given status code. Sets Content-Type to application/json automatically.
func MaxBodyBytes ¶
MaxBodyBytes returns a middleware that caps the request body at limit bytes using http.MaxBytesReader. The limit is enforced lazily as the body is read, so handlers (or BindJSON) must check the read/decode error and respond with http.StatusRequestEntityTooLarge themselves.
func Metrics ¶
func Metrics(recorder *MetricsRecorder) func(http.Handler) http.Handler
Metrics returns a middleware that records request count, concurrency, and cumulative duration. Pass a shared *MetricsRecorder to collect data.
func NewHttp ¶
func NewHttp(config ServerConfig) *httpServerImpl
NewHttp creates a new HTTP server for the given config. Production-ready timeouts are set by default (configurable via ServerConfig).
func NewRouter ¶
func NewRouter(config RouterConfig) *routerImpl
NewRouter creates a new router with the given configuration.
func Params ¶
Params extracts all path parameters from the request context as a map. Returns nil if no parameters were matched.
func QueryBool ¶
QueryBool returns the first value of the named query parameter as bool. Accepts "1", "t", "T", "true", "TRUE", "True" as true. Returns the default value if the parameter is missing.
func QueryFloat ¶
QueryFloat returns the first value of the named query parameter as float64, or the default value if the parameter is missing or not a valid number.
func QueryInt ¶
QueryInt returns the first value of the named query parameter as int, or the default value if the parameter is missing or not a valid integer.
func RateLimiter ¶
func RateLimiter(config RateLimiterConfig) func(http.Handler) http.Handler
RateLimiter returns a middleware that limits request rates using a token bucket algorithm, one bucket per KeyFunc(r) (or a single shared bucket if KeyFunc is nil). It returns 429 Too Many Requests when a bucket is empty.
func RecoverMiddleware ¶
RecoverMiddleware catches panics in the handler chain, logs the error, and returns a 500 Internal Server Error to the client. When stackTrace is true, the full stack trace is logged at error level.
func RemoteIP ¶
RemoteIP is a RateLimiterConfig.KeyFunc that keys by the request's remote IP address, with the port stripped. Falls back to the raw RemoteAddr if it cannot be parsed as host:port (e.g. in tests that set it directly).
func RequestID ¶
RequestID injects or preserves an X-Request-ID header in both the response and the request context. If the incoming request has no X-Request-ID, a unique ID is generated using the current timestamp.
func RequestLogger ¶
RequestLogger logs the HTTP method, path, and duration of each request. An optional logger can be provided; otherwise uses standard log output.
func SetCtx ¶
SetCtx stores a value in the request context and returns the modified request. Chainable: r = SetCtx(SetCtx(r, "a", 1), "b", 2).
func Text ¶
func Text(w http.ResponseWriter, code int, msg string)
Text writes a plain-text response with the given status code.
func URLParam ¶
URLParam returns the value of a single path parameter by name. Returns empty string if the parameter is not found.
func WriteError ¶
func WriteError(w http.ResponseWriter, code int, msg string)
WriteError writes a plain-text error response with the given status code.
Types ¶
type CORSConfig ¶
type CORSConfig struct {
AllowedOrigins []string
AllowedMethods []string
AllowedHeaders []string
ExposedHeaders []string
AllowCredentials bool
MaxAge int
}
CORSConfig configures CORS behavior for the CORS middleware.
type ContextKey ¶
type ContextKey string
ContextKey is used for request context value keys.
const ParamsContextKey ContextKey = "route_params"
ParamsContextKey is the context key for path parameters.
type HttpRouter ¶
type HttpRouter interface {
// Routes registers routes onto the given RouteRegister.
Routes(r RouteRegister)
}
HttpRouter is implemented by types that register routes onto a RouteRegister. Use it to encapsulate route groups in separate types (see example/user.go).
type HttpServer ¶
HttpServer wraps http.Server with graceful Start/Stop lifecycle.
type LogLevel ¶
type LogLevel int
LogLevel represents the minimum level a log message must have to be emitted.
type Logger ¶
type Logger interface {
// Errorf logs a message at ERROR level.
Errorf(format string, args ...any)
// Warnf logs a message at WARN level.
Warnf(format string, args ...any)
// Infof logs a message at INFO level.
Infof(format string, args ...any)
// Debugf logs a message at DEBUG level.
Debugf(format string, args ...any)
}
Logger is the interface for leveled logging in the router. Implementations should respect the receiver's own level filtering, or use the LogLevel from RouterConfig for filtering.
type MetricsRecorder ¶
type MetricsRecorder struct {
TotalRequests atomic.Int64
ActiveRequests atomic.Int64
TotalDuration atomic.Int64
}
MetricsRecorder records HTTP request metrics.
func (*MetricsRecorder) Snapshot ¶
func (m *MetricsRecorder) Snapshot() map[string]any
Snapshot returns a point-in-time snapshot of the metrics.
type MiddlewareFunc ¶
MiddlewareFunc wraps an http.Handler to add cross-cutting behavior.
func WithContext ¶
func WithContext(name string, value any) MiddlewareFunc
WithContext injects a key-value pair into the request context.
type RateLimiterConfig ¶
type RateLimiterConfig struct {
RequestsPerSecond int
Burst int
// KeyFunc extracts the rate-limit bucket key from a request, e.g. RemoteIP
// for per-client limiting. If nil, all requests share a single global
// bucket (pre-KeyFunc behavior).
KeyFunc func(*http.Request) string
}
RateLimiterConfig configures the rate limiter middleware.
type RouteInfo ¶
RouteInfo describes a single registered route, as returned by Routes(). It is a diagnostic snapshot (e.g. for logging all endpoints at startup), not part of the request-handling path.
type RouteRegister ¶
type RouteRegister interface {
Router
// Group creates a route group under path. args accepts:
// - func(Router) Router — the group callback
// - MiddlewareFunc, []MiddlewareFunc — group-level middleware
Group(path string, args ...any) Router
// Use registers middleware, handlers, or HttpRouter in a single call.
// Types are identified by type and can be mixed in any order.
Use(args ...any) RouteRegister
}
RouteRegister extends Router with group and middleware registration. Use accepts any combination of:
- HttpRouter — calls Routes(r) to register routes
- string — HTTP method or URL pattern
- http.Handler — the route handler
- MiddlewareFunc — middleware wrapping the handler
- []MiddlewareFunc — multiple middleware
type Router ¶
type Router interface {
// Get registers a GET handler at the given path.
Get(path string, args ...any) Router
// Post registers a POST handler at the given path.
Post(path string, args ...any) Router
// Put registers a PUT handler at the given path.
Put(path string, args ...any) Router
// Patch registers a PATCH handler at the given path.
Patch(path string, args ...any) Router
// Delete registers a DELETE handler at the given path.
Delete(path string, args ...any) Router
// Head registers a HEAD handler at the given path.
Head(path string, args ...any) Router
// Mount attaches a sub-handler under the given path prefix for all HTTP methods.
Mount(path string, sub http.Handler) Router
// Logger returns the router's Logger instance.
Logger() Logger
}
Router defines HTTP method handlers for route registration. Each method accepts args ...any which are identified by type:
- http.Handler — the route handler
- MiddlewareFunc — middleware wrapping the handler
- []MiddlewareFunc — multiple middleware
They can appear in any order.
type RouterAction ¶
RouterAction is a callback that receives a Router and returns it.
type RouterConfig ¶
type RouterConfig struct {
AssetDir string
AssetPath string
FS fs.FS
Logger Logger
LogLevel LogLevel
BaseContext context.Context
NotFoundHandler http.Handler
MethodNotAllowedHandler http.Handler
}
RouterConfig configures a new router instance.
type ServerConfig ¶
type ServerConfig struct {
Addr string
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
}
ServerConfig configures the HTTP server created by NewHttp. Zero values are replaced with sensible production defaults (10s ReadTimeout, 10s WriteTimeout, 60s IdleTimeout).