middleware

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const CSRFFormKey = "csrf_token"
View Source
const CSRFHeader = "X-CSRF-Token"

CSRF validates a token from header or form (plan: csrf middleware).

View Source
const RequestIDHeader = "X-Request-Id"

RequestIDHeader is the header used for request IDs.

Variables

This section is empty.

Functions

func BodyLimit

func BodyLimit(maxBytes int64) router.Middleware

BodyLimit restricts the maximum size of the request body. If the body exceeds maxBytes, the server returns 413 Request Entity Too Large.

Usage:

r.Use(middleware.BodyLimit(10 << 20)) // 10 MB

func CORS

func CORS(origins ...string) router.Middleware

CORS sets basic CORS headers. Accepts one or more allowed origins. When multiple origins are given, the middleware validates the request's Origin header against the list and only reflects a matching origin.

func CSRF

func CSRF(store CSRFStore) router.Middleware

CSRF returns middleware that validates CSRF token for non-GET/HEAD/OPTIONS. Token can be in header X-CSRF-Token or form field csrf_token. Use GenerateCSRFToken() to create tokens.

func DefaultKeyFn

func DefaultKeyFn(r *http.Request) string

DefaultKeyFn returns the client IP for rate limiting.

func GenerateCSRFToken

func GenerateCSRFToken() string

GenerateCSRFToken returns a new token (store in session and put in form/header).

func GetRequestID

func GetRequestID(c *http.Context) string

GetRequestID returns the request ID from the context store, or "".

func Gzip

func Gzip() router.Middleware

Gzip returns middleware that compresses response bodies using gzip when the client indicates support via Accept-Encoding. Small responses (< 256 B) are not compressed. Static assets served by CDN are typically excluded via route groups.

Usage:

r.Use(middleware.Gzip())

func Logger

func Logger() router.Middleware

Logger logs each request using the Nimbus structured logger package.

It emits one structured line per request with keyed fields (method, path, status, duration_ms, remote_addr) and — when the RequestID middleware runs earlier in the chain — a correlating request_id, so log lines can be joined to the X-Request-Id response header. The log level is chosen from the status code: 5xx → error, 4xx → warn, else info.

Applications can override the underlying logger via logger.Set for custom formatting or destinations.

func Metrics

func Metrics() router.Middleware

Metrics returns middleware that records Prometheus-compatible HTTP metrics:

  • http_requests_total (counter) labels: method, path, status
  • http_request_duration_seconds (histogram) labels: method, path, status
  • http_requests_in_flight (gauge)
  • http_response_size_bytes (counter) labels: method, path, status

func RateLimit

func RateLimit(limit int, window time.Duration, keyFn func(*http.Request) string) router.Middleware

RateLimit returns middleware that allows limit requests per window per key (keyFn extracts key from request, e.g. IP).

func RateLimitRedis

func RateLimitRedis(rdb *redis.Client, limit int, window time.Duration, keyFn func(*http.Request) string, failOpen ...bool) router.Middleware

RateLimitRedis returns middleware that rate-limits using Redis (suitable for multi-instance). keyFn extracts a key from the request (e.g. IP). Limit is requests per window. FailOpen controls behavior on Redis errors: true allows requests through, false (default) returns 503 Service Unavailable.

func Recover

func Recover() router.Middleware

Recover recovers from panics and returns a wrapped error so errors.Handler can render JSON or HTML consistently (and optional Telescope hooks).

func RequestID

func RequestID() router.Middleware

RequestID generates a unique request ID for every request and makes it available via the X-Request-Id response header and the context store (key: "request_id"). If the incoming request already carries a X-Request-Id header, that value is reused (useful behind load balancers).

func SecureHeaders

func SecureHeaders(cfg SecureHeadersConfig) router.Middleware

SecureHeaders sets production-grade security headers on every response.

Usage:

r.Use(middleware.SecureHeaders(middleware.DefaultSecureHeadersConfig()))

func Timeout

func Timeout(d time.Duration) router.Middleware

Timeout wraps each request with a context deadline. If the handler does not complete within the given duration, the request context is cancelled and the handler can detect it via c.Ctx().Err().

Usage:

r.Use(middleware.Timeout(30 * time.Second))

func TrustedProxies

func TrustedProxies(cidrs ...string) router.Middleware

TrustedProxies restricts which IP addresses are trusted to set forwarding headers (X-Forwarded-For, X-Real-Ip, X-Forwarded-Proto). When the request comes from an untrusted proxy, those headers are stripped to prevent spoofing.

Usage:

r.Use(middleware.TrustedProxies("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"))

Types

type CSRFStore

type CSRFStore interface {
	Valid(ctx context.Context, token string) bool
}

CSRFStore validates and optionally generates tokens (e.g. session-based).

type MemoryCSRFStore

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

MemoryCSRFStore keeps valid tokens in a process-global set (single-node only). It is a minimal helper: tokens are NOT bound to a session (any valid token authorizes any caller) and the set is not pruned, so it can grow unbounded. For production CSRF protection prefer shield.CSRFGuard, which uses a signed, session-bound double-submit cookie.

func NewMemoryCSRFStore

func NewMemoryCSRFStore() *MemoryCSRFStore

func (*MemoryCSRFStore) Create

func (m *MemoryCSRFStore) Create() string

func (*MemoryCSRFStore) Valid

func (m *MemoryCSRFStore) Valid(ctx context.Context, token string) bool

type SecureHeadersConfig

type SecureHeadersConfig struct {
	// HSTS sets Strict-Transport-Security. Default: "max-age=63072000; includeSubDomains".
	HSTS string

	// ContentTypeNoSniff sets X-Content-Type-Options: nosniff. Default: true.
	ContentTypeNoSniff bool

	// FrameOptions sets X-Frame-Options. Default: "DENY".
	FrameOptions string

	// XSSProtection sets X-XSS-Protection. Default: "1; mode=block".
	XSSProtection string

	// ReferrerPolicy sets Referrer-Policy. Default: "strict-origin-when-cross-origin".
	ReferrerPolicy string

	// ContentSecurityPolicy sets Content-Security-Policy. Default: "" (not set).
	ContentSecurityPolicy string

	// PermissionsPolicy sets Permissions-Policy. Default: "" (not set).
	PermissionsPolicy string
}

SecureHeadersConfig controls which security headers are set.

func DefaultSecureHeadersConfig

func DefaultSecureHeadersConfig() SecureHeadersConfig

DefaultSecureHeadersConfig returns sensible production defaults.

Jump to

Keyboard shortcuts

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