Documentation
¶
Overview ¶
Package rig provides a thin, zero-dependency wrapper around the Go standard library's net/http package. It offers ergonomic benefits similar to frameworks like Gin or Echo while relying purely on the Go standard library.
Index ¶
- func DefaultErrorHandler(c *Context, err error)
- func GetType[T any](c *Context, key string) (T, error)
- type CORSConfig
- type CheckFunc
- type CheckFuncContext
- type Context
- func (c *Context) Bind(v any) error
- func (c *Context) BindStrict(v any) error
- func (c *Context) Context() context.Context
- func (c *Context) Data(code int, contentType string, data []byte)
- func (c *Context) File(filepath string)
- func (c *Context) FormValue(key string) string
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) GetHeader(key string) string
- func (c *Context) Header() http.Header
- func (c *Context) JSON(code int, v any) error
- func (c *Context) Method() string
- func (c *Context) MustGet(key string) any
- func (c *Context) Param(name string) string
- func (c *Context) Path() string
- func (c *Context) PostFormValue(key string) string
- func (c *Context) Query(key string) string
- func (c *Context) QueryArray(key string) []string
- func (c *Context) QueryDefault(key, defaultValue string) string
- func (c *Context) Redirect(code int, url string)
- func (c *Context) Request() *http.Request
- func (c *Context) Set(key string, value any)
- func (c *Context) SetContext(ctx context.Context)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) Status(code int)
- func (c *Context) Write(data []byte) (int, error)
- func (c *Context) WriteString(s string) (int, error)
- func (c *Context) Writer() http.ResponseWriter
- func (c *Context) Written() bool
- type ErrorHandler
- type HandlerFunc
- type Health
- func (h *Health) AddLivenessCheck(name string, check CheckFunc)
- func (h *Health) AddLivenessCheckContext(name string, check CheckFuncContext)
- func (h *Health) AddLivenessCheckWithTimeout(name string, timeout time.Duration, check CheckFuncContext)
- func (h *Health) AddReadinessCheck(name string, check CheckFunc)
- func (h *Health) AddReadinessCheckContext(name string, check CheckFuncContext)
- func (h *Health) AddReadinessCheckWithTimeout(name string, timeout time.Duration, check CheckFuncContext)
- func (h *Health) LiveHandler() HandlerFunc
- func (h *Health) ReadyHandler() HandlerFunc
- type HealthConfig
- type LogFunc
- type MiddlewareFunc
- type RecoverConfig
- type RouteGroup
- func (g *RouteGroup) DELETE(path string, handler HandlerFunc)
- func (g *RouteGroup) GET(path string, handler HandlerFunc)
- func (g *RouteGroup) Group(prefix string) *RouteGroup
- func (g *RouteGroup) PATCH(path string, handler HandlerFunc)
- func (g *RouteGroup) POST(path string, handler HandlerFunc)
- func (g *RouteGroup) PUT(path string, handler HandlerFunc)
- func (g *RouteGroup) Use(mw ...MiddlewareFunc)
- type Router
- func (r *Router) DELETE(path string, handler HandlerFunc)
- func (r *Router) GET(path string, handler HandlerFunc)
- func (r *Router) Group(prefix string) *RouteGroup
- func (r *Router) HEAD(path string, handler HandlerFunc)
- func (r *Router) Handle(pattern string, handler HandlerFunc)
- func (r *Router) Handler() http.Handler
- func (r *Router) OPTIONS(path string, handler HandlerFunc)
- func (r *Router) PATCH(path string, handler HandlerFunc)
- func (r *Router) POST(path string, handler HandlerFunc)
- func (r *Router) PUT(path string, handler HandlerFunc)
- func (r *Router) Run(addr string) error
- func (r *Router) RunGracefully(addr string) error
- func (r *Router) RunUnsafe(addr string) error
- func (r *Router) RunWithConfig(config ServerConfig) error
- func (r *Router) RunWithGracefulShutdown(config ServerConfig) error
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) SetErrorHandler(handler ErrorHandler)
- func (r *Router) Static(path, root string, config ...StaticConfig)
- func (r *Router) Use(mw ...MiddlewareFunc)
- type ServerConfig
- type StaticConfig
- type TimeoutConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultErrorHandler ¶
DefaultErrorHandler is the default error handler that writes a 500 Internal Server Error response when a handler returns an error.
func GetType ¶
GetType retrieves a value from the context's key-value store and asserts its type safely using generics. This is the recommended way to retrieve typed values as it avoids panics from incorrect type assertions.
Example:
db, err := rig.GetType[*Database](c, "db")
if err != nil {
return err
}
db.Query(...)
Types ¶
type CORSConfig ¶
type CORSConfig struct {
// AllowOrigins is a list of origins that are allowed to access the resource.
// Supports three formats:
// - "*" to allow all origins
// - Exact match: "https://example.com"
// - Wildcard subdomain: "https://*.example.com" (matches any subdomain)
AllowOrigins []string
// AllowMethods is a list of methods allowed when accessing the resource.
AllowMethods []string
// AllowHeaders is a list of headers that can be used during the request.
AllowHeaders []string
}
CORSConfig defines the configuration for CORS middleware.
type CheckFunc ¶ added in v1.1.0
type CheckFunc func() error
CheckFunc is a function that returns nil if healthy, or an error if unhealthy.
type CheckFuncContext ¶ added in v1.6.0
CheckFuncContext is a function that accepts a context for cancellation/timeout support. Use this for health checks that make external calls (database pings, HTTP requests).
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context wraps http.ResponseWriter and *http.Request to provide convenient helper methods for HTTP handlers.
func (*Context) Bind ¶
Bind decodes the request body into the provided struct v. It expects the request body to be JSON and handles closing the body. The struct v should be a pointer.
By default, unknown fields in the JSON are silently ignored. For stricter APIs that should reject unknown fields, use BindStrict instead.
func (*Context) BindStrict ¶
BindStrict decodes the request body into the provided struct v, but returns an error if the JSON contains fields that are not present in the target struct. This is useful for security-sensitive APIs where you want to reject unexpected data.
Example error: "json: unknown field \"admin\""
func (*Context) Context ¶
Context returns the request's context.Context. This is crucial for passing to database drivers and other libraries that listen for cancellation signals.
func (*Context) Data ¶
Data writes raw bytes to the response with the specified status code and content type.
Example:
c.Data(http.StatusOK, "image/png", pngBytes)
func (*Context) File ¶
File writes the specified file into the response body. It uses http.ServeFile which handles Content-Type detection, range requests, and Last-Modified headers automatically.
Example:
c.File("./reports/monthly.pdf")
func (*Context) FormValue ¶
FormValue returns the first value for the named component of the query. POST and PUT body parameters take precedence over URL query string values. This is useful for handling HTML form submissions (application/x-www-form-urlencoded).
func (*Context) Get ¶
Get retrieves a value from the context's key-value store. Returns the value and a boolean indicating whether the key was found.
func (*Context) JSON ¶
JSON writes a JSON response with the given status code. It sets the Content-Type header to "application/json; charset=utf-8" and encodes the provided value v to the response body.
Note: Headers and status code can only be written once. If you've already called Status(), Write(), or WriteString(), the headers set here will be ignored.
func (*Context) MustGet ¶
MustGet retrieves a value from the context's key-value store. It panics if the key is not found. Use this only when you are certain the key exists (e.g., set by middleware earlier in the chain).
func (*Context) Param ¶
Param returns the value of a path parameter from the request. This uses Go 1.22+ PathValue feature.
func (*Context) PostFormValue ¶
PostFormValue returns the first value for the named component of the POST, PATCH, or PUT request body. URL query parameters are ignored. Use this when you want to explicitly read only from the request body.
func (*Context) Query ¶
Query returns the value of a query string parameter. Query parameters are parsed once and cached for efficient repeated access.
func (*Context) QueryArray ¶
QueryArray returns all values for a query string parameter. This is useful for parameters that can have multiple values like ?tag=a&tag=b. Query parameters are parsed once and cached for efficient repeated access.
func (*Context) QueryDefault ¶
QueryDefault returns the value of a query string parameter, or the default value if the parameter is not present or empty. Query parameters are parsed once and cached for efficient repeated access.
func (*Context) Redirect ¶
Redirect sends an HTTP redirect to the specified URL. The code should be a redirect status code (3xx), typically:
- http.StatusMovedPermanently (301) for permanent redirects
- http.StatusFound (302) for temporary redirects
- http.StatusSeeOther (303) for POST-to-GET redirects
- http.StatusTemporaryRedirect (307) to preserve method
- http.StatusPermanentRedirect (308) for permanent, method-preserving redirects
func (*Context) Set ¶
Set stores a value in the context's key-value store. The store is lazily initialized on first use to save memory.
func (*Context) SetContext ¶
SetContext updates the underlying request's context. Use this when middleware needs to set a timeout, deadline, or add tracing/telemetry data (e.g., OpenTelemetry spans) to the request.
Example:
ctx, cancel := context.WithTimeout(c.Context(), 5*time.Second) defer cancel() c.SetContext(ctx)
func (*Context) Status ¶
Status writes the HTTP status code to the response. This should be called before writing any body content.
func (*Context) WriteString ¶
WriteString writes a string to the response body.
func (*Context) Writer ¶
func (c *Context) Writer() http.ResponseWriter
Writer returns the underlying http.ResponseWriter.
type ErrorHandler ¶
ErrorHandler is a function type for handling errors returned by handlers. It receives the Context and the error, allowing custom error responses.
type HandlerFunc ¶
HandlerFunc is the custom handler signature for rig handlers. Unlike http.HandlerFunc, it accepts a *Context and returns an error, allowing handlers to return errors for centralized error handling.
type Health ¶ added in v1.1.0
type Health struct {
// contains filtered or unexported fields
}
Health manages liveness and readiness probes.
func NewHealth ¶ added in v1.1.0
func NewHealth() *Health
NewHealth creates a new Health manager with default configuration.
func NewHealthWithConfig ¶ added in v1.6.0
func NewHealthWithConfig(config HealthConfig) *Health
NewHealthWithConfig creates a new Health manager with custom configuration.
func (*Health) AddLivenessCheck ¶ added in v1.1.0
AddLivenessCheck adds a check that determines if the app is running (usually just a simple ping, or checking for deadlocks).
func (*Health) AddLivenessCheckContext ¶ added in v1.6.0
func (h *Health) AddLivenessCheckContext(name string, check CheckFuncContext)
AddLivenessCheckContext adds a context-aware liveness check. Use this for checks that make external calls and should respect timeouts.
func (*Health) AddLivenessCheckWithTimeout ¶ added in v1.6.0
func (h *Health) AddLivenessCheckWithTimeout(name string, timeout time.Duration, check CheckFuncContext)
AddLivenessCheckWithTimeout adds a liveness check with a custom timeout. This overrides the global CheckTimeout for this specific check.
func (*Health) AddReadinessCheck ¶ added in v1.1.0
AddReadinessCheck adds a check that must pass for the app to receive traffic (e.g., database connection, Redis, upstream API).
func (*Health) AddReadinessCheckContext ¶ added in v1.6.0
func (h *Health) AddReadinessCheckContext(name string, check CheckFuncContext)
AddReadinessCheckContext adds a context-aware readiness check. Use this for checks that make external calls and should respect timeouts.
Example:
health.AddReadinessCheckContext("database", func(ctx context.Context) error {
return db.PingContext(ctx)
})
func (*Health) AddReadinessCheckWithTimeout ¶ added in v1.6.0
func (h *Health) AddReadinessCheckWithTimeout(name string, timeout time.Duration, check CheckFuncContext)
AddReadinessCheckWithTimeout adds a readiness check with a custom timeout. This overrides the global CheckTimeout for this specific check.
func (*Health) LiveHandler ¶ added in v1.1.0
func (h *Health) LiveHandler() HandlerFunc
LiveHandler returns a Rig HandlerFunc for liveness probes.
func (*Health) ReadyHandler ¶ added in v1.1.0
func (h *Health) ReadyHandler() HandlerFunc
ReadyHandler returns a Rig HandlerFunc for readiness probes.
type HealthConfig ¶ added in v1.6.0
type HealthConfig struct {
// CheckTimeout is the maximum duration allowed for each individual health check.
// If a check exceeds this timeout, it is considered failed.
// Default: 5 seconds.
CheckTimeout time.Duration
// Parallel controls whether checks run concurrently.
// When true, all checks run in parallel (faster but uses more resources).
// When false, checks run sequentially (slower but predictable resource usage).
// Default: false (sequential).
Parallel bool
}
HealthConfig defines configuration for the Health manager.
func DefaultHealthConfig ¶ added in v1.6.0
func DefaultHealthConfig() HealthConfig
DefaultHealthConfig returns production-safe default configuration.
type LogFunc ¶ added in v1.8.0
LogFunc is a function type for logging server lifecycle events. It follows the same signature as log.Printf.
type MiddlewareFunc ¶
type MiddlewareFunc func(HandlerFunc) HandlerFunc
MiddlewareFunc is a function that wraps a HandlerFunc to provide additional functionality (logging, authentication, dependency injection, etc.). It follows the standard decorator pattern: it takes a handler and returns a new handler that wraps the original.
func CORS ¶
func CORS(config CORSConfig) MiddlewareFunc
CORS creates middleware that sets the necessary headers for Cross-Origin requests.
Supports wildcard subdomains in AllowOrigins:
r.Use(rig.CORS(rig.CORSConfig{
AllowOrigins: []string{
"https://*.example.com", // Matches any subdomain
"https://api.other.com", // Exact match
},
AllowMethods: []string{"GET", "POST"},
AllowHeaders: []string{"Content-Type", "Authorization"},
}))
func DefaultCORS ¶
func DefaultCORS() MiddlewareFunc
DefaultCORS creates CORS middleware with a permissive default configuration. It allows all origins and common HTTP methods and headers.
Example:
r := rig.New() r.Use(rig.DefaultCORS())
func Recover ¶
func Recover() MiddlewareFunc
Recover creates middleware that recovers from panics and returns a 500 error. This ensures the server never crashes from unhandled panics in handlers.
Panics are logged to stderr with a full stack trace for debugging. The client receives a generic 500 error to avoid leaking internal details.
Example:
r := rig.New() r.Use(rig.Recover())
func RecoverWithConfig ¶ added in v1.8.0
func RecoverWithConfig(config RecoverConfig) MiddlewareFunc
RecoverWithConfig creates recover middleware with custom configuration. This allows you to customize panic logging (e.g., send to structured logger).
Example:
r.Use(rig.RecoverWithConfig(rig.RecoverConfig{
Logger: func(err any, stack []byte) {
slog.Error("panic recovered",
"error", err,
"stack", string(stack),
)
},
}))
func Timeout ¶ added in v1.6.0
func Timeout(d time.Duration) MiddlewareFunc
Timeout creates middleware that cancels the request context if the handler takes longer than the specified duration.
This is crucial for preventing cascading failures when downstream services (databases, APIs) are slow. It works at the application layer, cancelling the context that handlers should be checking.
IMPORTANT: For this to work effectively, your handlers MUST:
- Use c.Context() when making external calls (DB queries, HTTP requests)
- Check ctx.Done() in long-running loops
- Stop writing to the response immediately when context is cancelled
WARNING: If your handler ignores ctx.Done() and continues writing to the response after timeout, a race condition may occur. This is the standard trade-off in high-performance Go frameworks (Gin, Echo use the same pattern). Always check ctx.Err() before writing responses in long-running handlers.
Example:
r.Use(rig.Timeout(5 * time.Second))
r.GET("/slow", func(c *rig.Context) error {
// This query will be cancelled if it takes > 5s
result, err := db.QueryContext(c.Context(), "SELECT ...")
if err != nil {
return err // Returns context.DeadlineExceeded if timed out
}
return c.JSON(http.StatusOK, result)
})
func TimeoutWithConfig ¶ added in v1.6.0
func TimeoutWithConfig(config TimeoutConfig) MiddlewareFunc
TimeoutWithConfig creates timeout middleware with custom configuration. This allows you to customize the timeout response.
Example:
r.Use(rig.TimeoutWithConfig(rig.TimeoutConfig{
Timeout: 5 * time.Second,
OnTimeout: func(c *rig.Context) error {
return c.JSON(http.StatusGatewayTimeout, map[string]string{
"error": "Request timed out",
"timeout": "5s",
})
},
}))
type RecoverConfig ¶ added in v1.8.0
type RecoverConfig struct {
// Logger is called when a panic is recovered.
// It receives the panic value and stack trace.
// If nil, logs to stderr using the standard log package.
// Set to a no-op function to disable logging:
// config.Logger = func(err any, stack []byte) {}
// Default: logs to stderr with "[RIG] PANIC:" prefix
Logger func(err any, stack []byte)
}
RecoverConfig defines the configuration for the Recover middleware.
type RouteGroup ¶
type RouteGroup struct {
// contains filtered or unexported fields
}
RouteGroup represents a group of routes with a common prefix. Groups can have their own middleware that applies only to routes in the group.
func (*RouteGroup) DELETE ¶
func (g *RouteGroup) DELETE(path string, handler HandlerFunc)
DELETE registers a handler for DELETE requests at the given path within the group. The path must be empty or begin with '/'. Panics if the path is invalid.
func (*RouteGroup) GET ¶
func (g *RouteGroup) GET(path string, handler HandlerFunc)
GET registers a handler for GET requests at the given path within the group. The path must be empty or begin with '/'. Panics if the path is invalid.
func (*RouteGroup) Group ¶
func (g *RouteGroup) Group(prefix string) *RouteGroup
Group creates a nested route group with an additional prefix. The nested group inherits the parent group's middleware. The prefix must begin with '/'. Panics if the prefix is invalid.
func (*RouteGroup) PATCH ¶
func (g *RouteGroup) PATCH(path string, handler HandlerFunc)
PATCH registers a handler for PATCH requests at the given path within the group. The path must be empty or begin with '/'. Panics if the path is invalid.
func (*RouteGroup) POST ¶
func (g *RouteGroup) POST(path string, handler HandlerFunc)
POST registers a handler for POST requests at the given path within the group. The path must be empty or begin with '/'. Panics if the path is invalid.
func (*RouteGroup) PUT ¶
func (g *RouteGroup) PUT(path string, handler HandlerFunc)
PUT registers a handler for PUT requests at the given path within the group. The path must be empty or begin with '/'. Panics if the path is invalid.
func (*RouteGroup) Use ¶
func (g *RouteGroup) Use(mw ...MiddlewareFunc)
Use appends one or more middleware to the group's middleware stack. These middleware only apply to routes registered on this group.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router wraps http.ServeMux to provide a convenient API for routing HTTP requests with the custom HandlerFunc signature.
func (*Router) DELETE ¶
func (r *Router) DELETE(path string, handler HandlerFunc)
DELETE registers a handler for DELETE requests at the given path. The path must begin with '/'. Panics if the path is invalid.
func (*Router) GET ¶
func (r *Router) GET(path string, handler HandlerFunc)
GET registers a handler for GET requests at the given path. The path must begin with '/'. Panics if the path is invalid.
func (*Router) Group ¶
func (r *Router) Group(prefix string) *RouteGroup
Group creates a new route group with the given prefix. All routes registered on the group will have the prefix prepended. The prefix must begin with '/'. Panics if the prefix is invalid.
func (*Router) HEAD ¶
func (r *Router) HEAD(path string, handler HandlerFunc)
HEAD registers a handler for HEAD requests at the given path. The path must begin with '/'. Panics if the path is invalid.
func (*Router) Handle ¶
func (r *Router) Handle(pattern string, handler HandlerFunc)
Handle registers a handler for the given pattern with any HTTP method. The pattern follows Go 1.22+ ServeMux patterns (e.g., "GET /users/{id}"). The handler is wrapped with all registered middleware before being added.
func (*Router) OPTIONS ¶
func (r *Router) OPTIONS(path string, handler HandlerFunc)
OPTIONS registers a handler for OPTIONS requests at the given path. The path must begin with '/'. Panics if the path is invalid.
func (*Router) PATCH ¶
func (r *Router) PATCH(path string, handler HandlerFunc)
PATCH registers a handler for PATCH requests at the given path. The path must begin with '/'. Panics if the path is invalid.
func (*Router) POST ¶
func (r *Router) POST(path string, handler HandlerFunc)
POST registers a handler for POST requests at the given path. The path must begin with '/'. Panics if the path is invalid.
func (*Router) PUT ¶
func (r *Router) PUT(path string, handler HandlerFunc)
PUT registers a handler for PUT requests at the given path. The path must begin with '/'. Panics if the path is invalid.
func (*Router) Run ¶
Run starts the HTTP server on the given address with production-safe default timeouts. This protects against Slowloris attacks and connection leaks.
For custom timeouts (e.g., long-polling endpoints), use RunWithConfig instead.
Default timeouts applied:
- ReadTimeout: 5s
- WriteTimeout: 10s
- IdleTimeout: 120s
- ReadHeaderTimeout: 2s
- MaxHeaderBytes: 1MB
func (*Router) RunGracefully ¶ added in v1.7.0
RunGracefully starts the HTTP server with production-safe defaults and waits for a termination signal (SIGINT or SIGTERM) to shut down gracefully.
It ensures that active connections are given time to complete before the process exits. This is the recommended method for production deployments, especially in containerized environments (Docker, Kubernetes).
The server will:
- Listen for SIGINT (Ctrl+C) and SIGTERM (Docker stop, Kubernetes terminate)
- Stop accepting new connections when a signal is received
- Wait up to 5 seconds for active requests to complete
- Forcefully close remaining connections after the timeout
Example:
func main() {
r := rig.New()
r.GET("/", handler)
if err := r.RunGracefully(":8080"); err != nil {
log.Fatal(err)
}
}
func (*Router) RunUnsafe ¶ added in v1.6.0
RunUnsafe starts the HTTP server without any timeouts. WARNING: This is only for development or testing. In production, this makes your server vulnerable to Slowloris attacks and connection leaks. Use Run() or RunWithConfig() instead.
func (*Router) RunWithConfig ¶ added in v1.6.0
func (r *Router) RunWithConfig(config ServerConfig) error
RunWithConfig starts the HTTP server with specific configuration. This is the recommended method for production deployments where you need custom timeouts (e.g., long-polling, file uploads, streaming responses).
Example:
config := rig.DefaultServerConfig() config.Addr = ":8080" config.WriteTimeout = 30 * time.Second // Allow longer responses r.RunWithConfig(config)
func (*Router) RunWithGracefulShutdown ¶ added in v1.7.0
func (r *Router) RunWithGracefulShutdown(config ServerConfig) error
RunWithGracefulShutdown starts the server with specific configuration and handles graceful shutdown automatically. Use this when you need custom timeouts or shutdown behavior.
Example:
config := rig.DefaultServerConfig() config.Addr = ":8080" config.WriteTimeout = 30 * time.Second // Allow longer responses config.ShutdownTimeout = 10 * time.Second // More time for shutdown r.RunWithGracefulShutdown(config)
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements the http.Handler interface. This allows the Router to be used directly with http.ListenAndServe.
func (*Router) SetErrorHandler ¶
func (r *Router) SetErrorHandler(handler ErrorHandler)
SetErrorHandler sets a custom error handler for the router. This handler is called when a HandlerFunc returns an error.
func (*Router) Static ¶
func (r *Router) Static(path, root string, config ...StaticConfig)
Static registers a route to serve static files from a directory. path is the URL path prefix (e.g., "/assets"). root is the local file system directory (e.g., "./public"). config is an optional StaticConfig for setting cache headers.
Example:
r.Static("/assets", "./public")
// GET /assets/css/style.css -> serves ./public/css/style.css
With cache control (recommended for production):
r.Static("/assets", "./public", rig.StaticConfig{
CacheControl: "public, max-age=31536000", // 1 year
})
func (*Router) Use ¶
func (r *Router) Use(mw ...MiddlewareFunc)
Use appends one or more middleware to the router's middleware stack. Middleware are executed in the order they are added.
type ServerConfig ¶ added in v1.6.0
type ServerConfig struct {
// Addr is the TCP address to listen on (e.g., ":8080" or "127.0.0.1:8080").
Addr string
// ReadTimeout is the maximum duration for reading the entire request,
// including the body. Setting this too low (e.g., 5s) will kill file uploads
// on slow connections. Use ReadHeaderTimeout for Slowloris protection instead.
// Default: 0 (no timeout - body reads are not time-limited).
ReadTimeout time.Duration
// WriteTimeout is the maximum duration before timing out writes of the
// response. This prevents slow clients from consuming server resources.
// Default: 10 seconds.
WriteTimeout time.Duration
// IdleTimeout is the maximum amount of time to wait for the next request
// when keep-alives are enabled. If zero, the value of ReadTimeout is used.
// Default: 120 seconds.
IdleTimeout time.Duration
// ReadHeaderTimeout is the amount of time allowed to read request headers.
// This is the critical defense against Slowloris attacks where attackers
// send headers very slowly to exhaust server resources.
// Default: 5 seconds.
ReadHeaderTimeout time.Duration
// MaxHeaderBytes controls the maximum number of bytes the server will
// read parsing the request header's keys and values.
// Default: 1MB (1 << 20).
MaxHeaderBytes int
// ShutdownTimeout is the maximum duration to wait for active connections
// to finish during graceful shutdown. After this timeout, the server
// forcefully closes remaining connections.
// Only used by RunGracefully and RunWithGracefulShutdown.
// Default: 5 seconds.
ShutdownTimeout time.Duration
// Logger is called to log server lifecycle events (startup, shutdown).
// If nil, logs to stderr using the standard log package.
// Set to a no-op function to disable logging:
// config.Logger = func(format string, args ...any) {}
// Default: log.Printf
Logger LogFunc
}
ServerConfig holds the configuration for the HTTP server. Use DefaultServerConfig() to get production-safe defaults that protect against Slowloris attacks and connection leaks.
func DefaultServerConfig ¶ added in v1.6.0
func DefaultServerConfig() ServerConfig
DefaultServerConfig returns production-safe default timeouts. These settings protect against Slowloris attacks while remaining permissive for legitimate slow clients (e.g., mobile file uploads).
The defaults are:
- ReadTimeout: 0 - no body read timeout (use Timeout middleware for request limits)
- ReadHeaderTimeout: 5s - critical Slowloris protection (headers only)
- WriteTimeout: 10s - prevents slow response consumption
- IdleTimeout: 120s - allows keep-alive but not indefinitely
- MaxHeaderBytes: 1MB - prevents header size attacks
- ShutdownTimeout: 5s - time for graceful shutdown
- Logger: log.Printf - logs to stderr
type StaticConfig ¶ added in v1.9.0
type StaticConfig struct {
// CacheControl sets the Cache-Control header for static files.
// Common values:
// - "public, max-age=31536000" (1 year, for versioned assets)
// - "public, max-age=86400" (1 day)
// - "no-cache" (always revalidate)
// If empty, no Cache-Control header is set.
CacheControl string
}
StaticConfig holds configuration options for serving static files.
type TimeoutConfig ¶ added in v1.6.0
type TimeoutConfig struct {
// Timeout is the maximum duration allowed for the handler to complete.
// After this duration, the context is cancelled and an error response is sent.
Timeout time.Duration
// OnTimeout is called when the handler times out.
// If nil, a default JSON response with 504 Gateway Timeout is returned.
OnTimeout func(c *Context) error
}
TimeoutConfig defines the configuration for the Timeout middleware.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auth provides authentication middleware for the rig HTTP library.
|
Package auth provides authentication middleware for the rig HTTP library. |
|
Package logger provides HTTP request logging middleware for the rig framework.
|
Package logger provides HTTP request logging middleware for the rig framework. |
|
render
module
|
|
|
Package requestid provides middleware for generating and propagating request IDs.
|
Package requestid provides middleware for generating and propagating request IDs. |
|
swagger
module
|