Documentation
¶
Index ¶
- func APIKey(header string, validator func(key string) (any, bool)) ginji.Middleware
- func APIKeyWithConfig(config APIKeyConfig) ginji.Middleware
- func BasicAuth(users map[string]string) ginji.Middleware
- func BasicAuthWithConfig(config BasicAuthConfig) ginji.Middleware
- func BearerAuth(validator func(token string) (any, bool)) ginji.Middleware
- func BearerAuthWithConfig(config BearerAuthConfig) ginji.Middleware
- func BodyLimit(maxBytes int64) ginji.Middleware
- func BodyLimit1MB() ginji.Middleware
- func BodyLimit5MB() ginji.Middleware
- func BodyLimit10MB() ginji.Middleware
- func BodyLimit50MB() ginji.Middleware
- func BodyLimitWithConfig(config BodyLimitConfig) ginji.Middleware
- func CSRF() ginji.Middleware
- func CSRFToken(c *ginji.Context) string
- func CSRFWithConfig(config CSRFConfig) ginji.Middleware
- func GetRequestID(c *ginji.Context) string
- func Health() ginji.Middleware
- func HealthWithConfig(config HealthCheckConfig) ginji.Middleware
- func Logger() ginji.Middleware
- func LoggerWithConfig(config LoggerConfig) ginji.Middleware
- func RateLimit(max int, window time.Duration) ginji.Middleware
- func RateLimitByAPIKey(max int, window time.Duration, headerName string) ginji.Middleware
- func RateLimitByUser(max int, window time.Duration, userKey string) ginji.Middleware
- func RateLimitPerHour(max int) ginji.Middleware
- func RateLimitPerMinute(max int) ginji.Middleware
- func RateLimitPerSecond(max int) ginji.Middleware
- func RateLimitWithConfig(config RateLimiterConfig) ginji.Middleware
- func RequestID() ginji.Middleware
- func RequestIDWithConfig(config RequestIDConfig) ginji.Middleware
- func RequireRole(role string) ginji.Middleware
- func Secure() ginji.Middleware
- func SecureStrict() ginji.Middleware
- func SecureWithConfig(config SecureConfig) ginji.Middleware
- func SimpleHealthCheck(livePath, readyPath string) ginji.Middleware
- func Timeout(duration time.Duration) ginji.Middleware
- func TimeoutMinutes(minutes int) ginji.Middleware
- func TimeoutSeconds(seconds int) ginji.Middleware
- func TimeoutWithConfig(config TimeoutConfig) ginji.Middleware
- type APIKeyConfig
- type AuthConfig
- type BasicAuthConfig
- type BearerAuthConfig
- type BodyLimitConfig
- type CSP
- func (csp *CSP) BaseURI(sources ...string) *CSP
- func (csp *CSP) Build() string
- func (csp *CSP) ConnectSrc(sources ...string) *CSP
- func (csp *CSP) DefaultSrc(sources ...string) *CSP
- func (csp *CSP) FontSrc(sources ...string) *CSP
- func (csp *CSP) FormAction(sources ...string) *CSP
- func (csp *CSP) FrameSrc(sources ...string) *CSP
- func (csp *CSP) ImgSrc(sources ...string) *CSP
- func (csp *CSP) ObjectSrc(sources ...string) *CSP
- func (csp *CSP) ScriptSrc(sources ...string) *CSP
- func (csp *CSP) StyleSrc(sources ...string) *CSP
- func (csp *CSP) UpgradeInsecureRequests() *CSP
- type CSRFConfig
- type HealthCheckConfig
- type HealthChecker
- type HealthStatus
- type LoggerConfig
- type RateLimiterConfig
- type RequestIDConfig
- type SecureConfig
- type TimeoutConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func APIKeyWithConfig ¶
func APIKeyWithConfig(config APIKeyConfig) ginji.Middleware
APIKeyWithConfig returns middleware with custom API Key configuration.
func BasicAuth ¶
func BasicAuth(users map[string]string) ginji.Middleware
BasicAuth returns middleware for HTTP Basic Authentication.
func BasicAuthWithConfig ¶
func BasicAuthWithConfig(config BasicAuthConfig) ginji.Middleware
BasicAuthWithConfig returns middleware with custom Basic Auth configuration.
func BearerAuth ¶
func BearerAuth(validator func(token string) (any, bool)) ginji.Middleware
BearerAuth returns middleware for Bearer token authentication.
func BearerAuthWithConfig ¶
func BearerAuthWithConfig(config BearerAuthConfig) ginji.Middleware
BearerAuthWithConfig returns middleware with custom Bearer Auth configuration.
func BodyLimit ¶
func BodyLimit(maxBytes int64) ginji.Middleware
BodyLimit returns a middleware that limits the size of request bodies. Usage:
app.Use(middleware.BodyLimit(10 << 20)) // 10 MB limit
func BodyLimit1MB ¶
func BodyLimit1MB() ginji.Middleware
BodyLimit1MB returns middleware with 1MB limit.
func BodyLimit5MB ¶
func BodyLimit5MB() ginji.Middleware
BodyLimit5MB returns middleware with 5MB limit.
func BodyLimit10MB ¶
func BodyLimit10MB() ginji.Middleware
BodyLimit10MB returns middleware with 10MB limit.
func BodyLimit50MB ¶
func BodyLimit50MB() ginji.Middleware
BodyLimit50MB returns middleware with 50MB limit.
func BodyLimitWithConfig ¶
func BodyLimitWithConfig(config BodyLimitConfig) ginji.Middleware
BodyLimitWithConfig returns a middleware with custom configuration.
func CSRF ¶
func CSRF() ginji.Middleware
CSRF returns a CSRF protection middleware with default configuration.
func CSRFWithConfig ¶
func CSRFWithConfig(config CSRFConfig) ginji.Middleware
CSRFWithConfig returns a CSRF protection middleware with custom configuration.
func GetRequestID ¶
GetRequestID is a helper to get the request ID from context.
func Health ¶
func Health() ginji.Middleware
Health returns middleware with default health check endpoints.
func HealthWithConfig ¶
func HealthWithConfig(config HealthCheckConfig) ginji.Middleware
HealthWithConfig returns middleware with custom configuration.
func Logger ¶
func Logger() ginji.Middleware
Logger returns a middleware that logs HTTP requests using structured logging.
func LoggerWithConfig ¶
func LoggerWithConfig(config LoggerConfig) ginji.Middleware
LoggerWithConfig returns a middleware with custom logger configuration.
func RateLimit ¶
func RateLimit(max int, window time.Duration) ginji.Middleware
RateLimit returns a rate limiter middleware with specified max requests and window.
func RateLimitByAPIKey ¶
RateLimitByAPIKey returns middleware that limits by API key header.
func RateLimitByUser ¶
RateLimitByUser returns middleware that limits by user ID from context.
func RateLimitPerHour ¶
func RateLimitPerHour(max int) ginji.Middleware
RateLimitPerHour returns middleware that limits requests per hour.
func RateLimitPerMinute ¶
func RateLimitPerMinute(max int) ginji.Middleware
RateLimitPerMinute returns middleware that limits requests per minute.
func RateLimitPerSecond ¶
func RateLimitPerSecond(max int) ginji.Middleware
RateLimitPerSecond returns middleware that limits requests per second.
func RateLimitWithConfig ¶
func RateLimitWithConfig(config RateLimiterConfig) ginji.Middleware
RateLimitWithConfig returns a rate limiter middleware with custom configuration.
func RequestID ¶
func RequestID() ginji.Middleware
RequestID returns a request ID middleware with default configuration.
func RequestIDWithConfig ¶
func RequestIDWithConfig(config RequestIDConfig) ginji.Middleware
RequestIDWithConfig returns a request ID middleware with custom configuration.
func RequireRole ¶
func RequireRole(role string) ginji.Middleware
RequireRole returns middleware that checks if user has a specific role. Expects user to be a map[string]any with a "role" or "roles" field.
func Secure ¶
func Secure() ginji.Middleware
Secure returns a middleware that sets security headers with default configuration.
func SecureStrict ¶
func SecureStrict() ginji.Middleware
SecureStrict returns middleware with strict security headers for production.
func SecureWithConfig ¶
func SecureWithConfig(config SecureConfig) ginji.Middleware
SecureWithConfig returns a middleware that sets security headers with custom configuration.
func SimpleHealthCheck ¶
func SimpleHealthCheck(livePath, readyPath string) ginji.Middleware
SimpleHealthCheck returns a basic health check middleware for Kubernetes-style probes.
func Timeout ¶
func Timeout(duration time.Duration) ginji.Middleware
Timeout returns middleware that enforces a timeout on requests.
func TimeoutMinutes ¶
func TimeoutMinutes(minutes int) ginji.Middleware
TimeoutMinutes returns middleware with timeout in minutes.
func TimeoutSeconds ¶
func TimeoutSeconds(seconds int) ginji.Middleware
TimeoutSeconds returns middleware with timeout in seconds.
func TimeoutWithConfig ¶
func TimeoutWithConfig(config TimeoutConfig) ginji.Middleware
TimeoutWithConfig returns middleware with custom timeout configuration.
Types ¶
type APIKeyConfig ¶
type APIKeyConfig struct {
// Header name to look for the API key (e.g., "X-API-Key").
Header string
// Query parameter name to look for the API key (optional).
Query string
// Validator validates the API key and returns user info.
Validator func(key string) (any, bool)
// ContextKey to store authenticated user.
ContextKey string
}
APIKeyConfig defines configuration for API Key authentication.
type AuthConfig ¶
type AuthConfig struct {
// Validator is a function that validates credentials and returns user info.
Validator func(credentials string) (any, bool)
// Realm is the authentication realm for Basic Auth.
Realm string
// If nil, a default 401 response is sent.
Unauthorized func(*ginji.Context)
// ContextKey is the key used to store authenticated user in context.
ContextKey string
// SkipFunc allows skipping authentication for certain requests.
SkipFunc func(*ginji.Context) bool
}
AuthConfig defines the configuration for authentication middleware.
type BasicAuthConfig ¶
type BasicAuthConfig struct {
// Users is a map of allowed username:password pairs.
Users map[string]string
// Validator is a custom function to validate username/password.
// Takes precedence over Users map.
Validator func(username, password string) bool
// Realm for WWW-Authenticate header.
Realm string
// ContextKey to store authenticated username.
ContextKey string
}
BasicAuthConfig defines configuration for Basic Authentication.
type BearerAuthConfig ¶
type BearerAuthConfig struct {
// Validator validates the bearer token and returns user info.
Validator func(token string) (any, bool)
// ContextKey to store authenticated user.
ContextKey string
// Realm for WWW-Authenticate header.
Realm string
}
BearerAuthConfig defines configuration for Bearer token authentication.
type BodyLimitConfig ¶
type BodyLimitConfig struct {
// MaxBytes is the maximum allowed size of the request body in bytes.
MaxBytes int64
// ErrorMessage is the custom error message to return when limit is exceeded.
// If empty, a default message will be used.
ErrorMessage string
// StatusCode is the HTTP status code to return when limit is exceeded.
// Defaults to 413 (Request Entity Too Large).
StatusCode int
}
BodyLimitConfig defines the configuration for body limit middleware.
func DefaultBodyLimitConfig ¶
func DefaultBodyLimitConfig() BodyLimitConfig
DefaultBodyLimitConfig returns a default configuration with 4MB limit.
type CSP ¶
type CSP struct {
// contains filtered or unexported fields
}
CSP is a helper to build Content-Security-Policy headers.
func (*CSP) ConnectSrc ¶
ConnectSrc sets the connect-src directive.
func (*CSP) DefaultSrc ¶
DefaultSrc sets the default-src directive.
func (*CSP) FormAction ¶
FormAction sets the form-action directive.
func (*CSP) UpgradeInsecureRequests ¶
UpgradeInsecureRequests adds the upgrade-insecure-requests directive.
type CSRFConfig ¶
type CSRFConfig struct {
// TokenLength is the length of CSRF tokens in bytes.
// Default: 32
TokenLength int
// TokenLookup specifies how to extract the token from the request.
// Formats: "header:<name>", "form:<name>", "query:<name>"
// Default: "header:X-CSRF-Token"
TokenLookup string
// CookieName is the name of the CSRF cookie.
// Default: "_csrf"
CookieName string
// CookiePath is the path for the CSRF cookie.
// Default: "/"
CookiePath string
// CookieDomain is the domain for the CSRF cookie.
CookieDomain string
// CookieSecure sets the Secure flag on the cookie.
// Default: false
CookieSecure bool
// CookieHTTPOnly sets the HttpOnly flag on the cookie.
// Default: true
CookieHTTPOnly bool
// CookieSameSite sets the SameSite attribute on the cookie.
// Default: http.SameSiteStrictMode
CookieSameSite http.SameSite
// CookieMaxAge is the max age of the CSRF cookie in seconds.
// Default: 86400 (24 hours)
CookieMaxAge int
// ContextKey is the key used to store the CSRF token in the context.
// Default: "csrf"
ContextKey string
// ErrorHandler is called when CSRF validation fails.
// If nil, a default 403 response is sent.
ErrorHandler func(*ginji.Context)
}
CSRFConfig defines configuration for CSRF protection middleware.
func DefaultCSRFConfig ¶
func DefaultCSRFConfig() CSRFConfig
DefaultCSRFConfig returns default CSRF configuration.
type HealthCheckConfig ¶
type HealthCheckConfig struct {
// LivenessPath is the path for liveness probes.
// Default: "/health/live"
LivenessPath string
// ReadinessPath is the path for readiness probes.
// Default: "/health/ready"
ReadinessPath string
// Checkers are health check functions to run for readiness.
// Liveness checks are typically simpler (just checking if the app is running).
Checkers map[string]HealthChecker
// Timeout is the maximum time to wait for all health checks.
// Default: 5 seconds
Timeout time.Duration
// DisableLiveness disables the liveness endpoint.
DisableLiveness bool
// DisableReadiness disables the readiness endpoint.
DisableReadiness bool
}
HealthCheckConfig defines the configuration for health check middleware.
func DefaultHealthCheckConfig ¶
func DefaultHealthCheckConfig() HealthCheckConfig
DefaultHealthCheckConfig returns default health check configuration.
func (*HealthCheckConfig) AddHealthChecker ¶
func (config *HealthCheckConfig) AddHealthChecker(name string, checker HealthChecker)
AddHealthChecker adds a health checker to the configuration.
type HealthChecker ¶
type HealthChecker func() error
HealthChecker is a function that checks the health of a component. It should return an error if the component is unhealthy.
type HealthStatus ¶
type HealthStatus struct {
Status string `json:"status"`
Checks map[string]string `json:"checks,omitempty"`
Message string `json:"message,omitempty"`
Time string `json:"time"`
}
HealthStatus represents the health status response.
type LoggerConfig ¶
type LoggerConfig struct {
// Logger is the slog logger instance to use. If nil, uses engine's logger.
Logger *slog.Logger
// SkipPaths is a list of paths to skip logging (e.g., health checks).
SkipPaths []string
// SkipFunc allows custom logic to skip logging for certain requests.
SkipFunc func(*ginji.Context) bool
}
LoggerConfig defines configuration for the logger middleware.
func DefaultLoggerConfig ¶
func DefaultLoggerConfig() LoggerConfig
DefaultLoggerConfig returns the default logger configuration.
type RateLimiterConfig ¶
type RateLimiterConfig struct {
// Max is the maximum number of requests allowed in the time window.
Max int
// Window is the time window for rate limiting.
Window time.Duration
// KeyFunc is a function that returns the key for rate limiting.
// Common keys: IP address, user ID, API key.
// Default: uses client IP
KeyFunc func(*ginji.Context) string
// ErrorMessage is returned when rate limit is exceeded.
ErrorMessage string
// StatusCode is the HTTP status code when rate limit is exceeded.
// Default: 429 Too Many Requests
StatusCode int
// SkipFunc allows skipping rate limiting for certain requests.
SkipFunc func(*ginji.Context) bool
// Headers determines whether to add rate limit headers to the response.
Headers bool
// TrustedProxies is a list of trusted proxy IP addresses.
// If empty, X-Forwarded-For headers are not trusted.
TrustedProxies []string
}
RateLimiterConfig defines the configuration for rate limiter middleware.
func DefaultRateLimiterConfig ¶
func DefaultRateLimiterConfig() RateLimiterConfig
DefaultRateLimiterConfig returns default rate limiter configuration.
type RequestIDConfig ¶
type RequestIDConfig struct {
// Generator is a function that generates unique request IDs.
// If nil, a default UUID-like generator is used.
Generator func() string
// RequestIDHeader is the header name for the request ID.
// Default: "X-Request-ID"
RequestIDHeader string
// ResponseIDHeader is the header name for the response ID.
// Default: "X-Request-ID"
ResponseIDHeader string
// ContextKey is the key to store the request ID in context.
// Default: "request_id"
ContextKey string
}
RequestIDConfig defines configuration for request ID middleware.
func DefaultRequestIDConfig ¶
func DefaultRequestIDConfig() RequestIDConfig
DefaultRequestIDConfig returns default request ID configuration.
type SecureConfig ¶
type SecureConfig struct {
// XSSProtection provides XSS protection header.
// Default: "1; mode=block"
XSSProtection string
// ContentTypeNosniff provides X-Content-Type-Options header.
// Default: "nosniff"
ContentTypeNosniff string
// XFrameOptions provides X-Frame-Options header.
// Possible values: "DENY", "SAMEORIGIN", "ALLOW-FROM uri"
// Default: "SAMEORIGIN"
XFrameOptions string
// HSTSMaxAge sets the Strict-Transport-Security header max-age value in seconds.
// Default: 0 (disabled)
HSTSMaxAge int
// HSTSIncludeSubdomains adds includeSubDomains to the HSTS header.
// Default: false
HSTSIncludeSubdomains bool
// HSTSPreload adds preload to the HSTS header.
// Default: false
HSTSPreload bool
// ContentSecurityPolicy sets the Content-Security-Policy header.
// Default: "" (not set)
ContentSecurityPolicy string
// ReferrerPolicy sets the Referrer-Policy header.
// Default: "" (not set)
ReferrerPolicy string
// PermissionsPolicy sets the Permissions-Policy header.
// Default: "" (not set)
PermissionsPolicy string
// CrossOriginEmbedderPolicy sets the Cross-Origin-Embedder-Policy header.
// Possible values: "unsafe-none", "require-corp", "credentialless"
// Default: "" (not set)
CrossOriginEmbedderPolicy string
// CrossOriginOpenerPolicy sets the Cross-Origin-Opener-Policy header.
// Possible values: "unsafe-none", "same-origin-allow-popups", "same-origin"
// Default: "" (not set)
CrossOriginOpenerPolicy string
// CrossOriginResourcePolicy sets the Cross-Origin-Resource-Policy header.
// Possible values: "same-site", "same-origin", "cross-origin"
// Default: "" (not set)
CrossOriginResourcePolicy string
}
SecureConfig defines the configuration for security headers middleware.
func DefaultSecureConfig ¶
func DefaultSecureConfig() SecureConfig
DefaultSecureConfig returns a default secure configuration.
type TimeoutConfig ¶
type TimeoutConfig struct {
// Timeout is the duration before the request times out.
Timeout time.Duration
// ErrorMessage is the message returned when a timeout occurs.
ErrorMessage string
// StatusCode is the HTTP status code for timeout responses.
// Default: 408 Request Timeout or 504 Gateway Timeout
StatusCode int
// SkipFunc allows skipping timeout for certain requests.
SkipFunc func(*ginji.Context) bool
}
TimeoutConfig defines the configuration for timeout middleware.
func DefaultTimeoutConfig ¶
func DefaultTimeoutConfig() TimeoutConfig
DefaultTimeoutConfig returns default timeout configuration.