guard

package
v5.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultSecurityHeaders = SecurityHeadersConfig{
	ContentSecurityPolicy:   "default-src 'self'",
	XContentTypeOptions:     "nosniff",
	XFrameOptions:           "DENY",
	ReferrerPolicy:          "strict-origin-when-cross-origin",
	PermissionsPolicy:       "geolocation=(), camera=(), microphone=()",
	HSTS:                    HSTSConfig{MaxAge: 63072000, IncludeSubDomains: true, Preload: true},
	CrossOriginOpenerPolicy: "same-origin",
}

DefaultSecurityHeaders provides secure defaults for all security headers.

Functions

func CORS

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

CORS returns middleware that handles Cross-Origin Resource Sharing. It responds to OPTIONS preflight requests with 204 and sets appropriate CORS headers on matching-origin requests. Panics if AllowOrigins is empty or if AllowCredentials is used with wildcard origin.

func IPFilter

func IPFilter(cfg IPFilterConfig) func(http.Handler) http.Handler

IPFilter returns middleware that filters requests by client IP address. Deny rules are evaluated first and take precedence over Allow rules. When only Allow is set, all non-matching IPs are rejected. When only Deny is set, all non-matching IPs are allowed. Panics if both Allow and Deny are empty, or if any CIDR is invalid.

func MaxBody

func MaxBody(maxBytes int64) func(http.Handler) http.Handler

MaxBody returns middleware that rejects requests with a body exceeding maxBytes with 413 Payload Too Large.

func RateLimit

func RateLimit(cfg RateLimitConfig) func(http.Handler) http.Handler

RateLimit returns middleware enforcing per-key rate limiting with token bucket. Panics if Rate, Window, KeyFunc, or MaxKeys are invalid.

func SecurityHeaders

func SecurityHeaders(cfg SecurityHeadersConfig) func(http.Handler) http.Handler

SecurityHeaders returns middleware that sets security-related HTTP headers before calling the next handler.

func Timeout

func Timeout(d time.Duration) func(http.Handler) http.Handler

Timeout returns middleware that sets a context deadline on the request and actively returns 504 Gateway Timeout if the handler does not complete before the deadline fires. If the caller already set a tighter deadline, the tighter deadline wins and no new deadline is applied.

Types

type CORSConfig

type CORSConfig struct {
	AllowOrigins     []string      // REQUIRED: list of allowed origins, or ["*"] for wildcard
	AllowMethods     []string      // defaults to GET, POST, HEAD
	AllowHeaders     []string      // defaults to Origin, Content-Type, Accept
	MaxAge           time.Duration // preflight cache duration
	AllowCredentials bool          // sets Access-Control-Allow-Credentials: true
}

CORSConfig configures the CORS middleware.

type HSTSConfig

type HSTSConfig struct {
	MaxAge            int  // max-age in seconds
	IncludeSubDomains bool // include subdomains directive
	Preload           bool // preload directive
}

HSTSConfig configures the Strict-Transport-Security header.

type IPFilterConfig

type IPFilterConfig struct {
	Allow   []string // CIDR notation whitelist
	Deny    []string // CIDR notation blacklist (evaluated first)
	KeyFunc KeyFunc  // optional: custom IP extraction (e.g., XForwardedFor); defaults to RemoteAddr
}

IPFilterConfig configures the IP filter middleware.

type KeyFunc

type KeyFunc func(r *http.Request) string

KeyFunc extracts a rate limit key from an HTTP request.

func HeaderKey

func HeaderKey(header string) KeyFunc

HeaderKey returns a KeyFunc using the value of a request header as the key. Falls back to RemoteAddr if the header is absent.

func RemoteAddr

func RemoteAddr() KeyFunc

RemoteAddr returns a KeyFunc that uses the request's RemoteAddr (without port).

func XForwardedFor

func XForwardedFor(trustedCIDRs ...string) KeyFunc

XForwardedFor returns a KeyFunc that reads the client IP from X-Forwarded-For, but only if RemoteAddr is within a trusted CIDR range. It walks the X-Forwarded-For chain from right to left, returning the rightmost IP that is NOT in the trusted CIDRs — this is the last hop before entering the trusted proxy chain and is resistant to client-side header spoofing.

Falls back to RemoteAddr if untrusted, if X-Forwarded-For is absent, or if no valid non-trusted IP is found.

type RateLimitConfig

type RateLimitConfig struct {
	Rate    int
	Window  time.Duration
	KeyFunc KeyFunc // REQUIRED
	MaxKeys int     // REQUIRED: upper bound on tracked keys
}

RateLimitConfig configures the rate limiter.

type SecurityHeadersConfig

type SecurityHeadersConfig struct {
	ContentSecurityPolicy   string     // Content-Security-Policy header value
	XContentTypeOptions     string     // X-Content-Type-Options header value
	XFrameOptions           string     // X-Frame-Options header value
	ReferrerPolicy          string     // Referrer-Policy header value
	PermissionsPolicy       string     // Permissions-Policy header value
	HSTS                    HSTSConfig // Strict-Transport-Security config
	CrossOriginOpenerPolicy string     // Cross-Origin-Opener-Policy header value
}

SecurityHeadersConfig configures the security headers middleware.

Jump to

Keyboard shortcuts

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