middleware

package
v0.1.2 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Auth

func Auth(validator auth.TokenValidator, opts ...AuthOption) gin.HandlerFunc

Auth returns a Gin middleware that validates tokens and stores the parsed claims in the request context. Claims are retrieved in handlers with:

claims, ok := authctx.Get[*MyClaims](c.Request.Context())

The validator is any auth.TokenValidator implementation — JWT, OIDC, API key, etc. For JWT, use jwtService.AsValidator().

func GinBodySizeLimit

func GinBodySizeLimit(maxSize string) gin.HandlerFunc

GinBodySizeLimit returns a Gin middleware for body size limiting. Prefer using BodySizeLimit() at the server level via ApplyMiddleware() which covers all routes. Use this only when you need it on the Gin engine directly.

func GinCORS

func GinCORS(cfg *CORSConfig) gin.HandlerFunc

GinCORS returns a Gin middleware for CORS. Prefer using CORS() at the server level via ApplyMiddleware() which covers all routes. Use this only when you need CORS on the Gin engine directly.

func GinRecovery

func GinRecovery() gin.HandlerFunc

GinRecovery returns a Gin middleware that recovers from panics. Prefer using Recovery() at the server level via ApplyMiddleware() which covers all routes. Use this only when you need recovery on the Gin engine directly.

func GinRequestID

func GinRequestID() gin.HandlerFunc

GinRequestID returns a Gin middleware for request-ID injection. Prefer using RequestID() at the server level via ApplyMiddleware() which covers all routes. Use this only when you need it on the Gin engine directly.

func GinRequestLogger

func GinRequestLogger() gin.HandlerFunc

GinRequestLogger returns a Gin middleware for request logging. Prefer using RequestLogger() at the server level via ApplyMiddleware() which covers all routes. Use this only when you need logging on the Gin engine directly.

func GinWrap

func GinWrap(mw Middleware) gin.HandlerFunc

GinWrap adapts a standard Middleware for use in a Gin middleware chain. Use this when you need to apply a Middleware directly on the Gin engine instead of at the server handler level.

Note: middleware that wraps http.ResponseWriter (e.g. RequestLogger) may not fully integrate with gin.Context.Writer. Prefer applying such middleware at the server level via ApplyMiddleware().

func IPBasedKey

func IPBasedKey(c *gin.Context) string

IPBasedKey extracts the client IP for use as a rate limit key.

func OptionalAuth

func OptionalAuth(validator auth.TokenValidator, opts ...AuthOption) gin.HandlerFunc

OptionalAuth validates a token if present but allows unauthenticated requests. If valid, claims are stored in context. If absent or invalid, request proceeds.

func RateLimit

func RateLimit(cfg RateLimitConfig) gin.HandlerFunc

RateLimit returns a Gin middleware that applies per-key sliding-window rate limiting.

func Require

func Require(check func(c *gin.Context) bool) gin.HandlerFunc

Require is a generic guard middleware. It calls the check function and returns 403 Forbidden if the check returns false.

This is the most flexible guard — use it for any authorization logic:

router.Use(middleware.Require(func(c *gin.Context) bool {
    claims, ok := authctx.Get[*MyClaims](c.Request.Context())
    return ok && claims.IsAdmin()
}))

func RequirePermission

func RequirePermission(checker authz.Checker, required string, subjectExtractor func(*gin.Context) string) gin.HandlerFunc

RequirePermission is a guard middleware that uses an authz.Checker. The subjectExtractor reads the subject (e.g., role name) from the request, and the checker determines if the subject has the required permission.

Example:

checker := authz.NewMapChecker(rolePermissions)
router.Use(middleware.RequirePermission(
    checker,
    "article:write",
    func(c *gin.Context) string {
        claims, _ := authctx.Get[*MyClaims](c.Request.Context())
        return claims.Role
    },
))

func UserBasedKey

func UserBasedKey(c *gin.Context) string

UserBasedKey extracts the user_id from the context, falling back to client IP.

Types

type AuthOption

type AuthOption func(*authOptions)

AuthOption configures the Auth middleware.

func WithHeaderName

func WithHeaderName(name string) AuthOption

WithHeaderName sets the header to read the token from (default: "Authorization").

func WithScheme

func WithScheme(scheme string) AuthOption

WithScheme sets the expected token scheme (default: "Bearer"). Set to empty string to read the raw header value without scheme parsing.

func WithSkipPaths

func WithSkipPaths(paths ...string) AuthOption

WithSkipPaths skips authentication for requests whose path starts with any of the given prefixes.

type CORSConfig

type CORSConfig struct {
	AllowedOrigins   []string `yaml:"allowed_origins" mapstructure:"allowed_origins"`
	AllowedMethods   []string `yaml:"allowed_methods" mapstructure:"allowed_methods"`
	AllowedHeaders   []string `yaml:"allowed_headers" mapstructure:"allowed_headers"`
	AllowCredentials bool     `yaml:"allow_credentials" mapstructure:"allow_credentials"`
}

CORSConfig holds CORS middleware configuration.

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware wraps an http.Handler with additional behavior. This is the standard Go middleware signature and the single middleware type for the entire server — it works with all routes including REST (Gin), ConnectRPC, and any other http.Handler mounted on the ServeMux.

func BodySizeLimit

func BodySizeLimit(maxSize string) Middleware

BodySizeLimit returns middleware that restricts the request body to the given size string (e.g. "10MB", "512KB", "1GB").

func CORS

func CORS(cfg *CORSConfig) Middleware

CORS returns middleware that sets CORS headers and handles OPTIONS preflight.

func Chain

func Chain(middlewares ...Middleware) Middleware

Chain composes multiple middleware. The first in the list is the outermost (runs first on a request, last on a response).

func Recovery

func Recovery(log *logger.Logger) Middleware

Recovery returns middleware that recovers from panics and returns a 500 JSON error response.

func RequestID

func RequestID() Middleware

RequestID returns middleware that ensures every request has an X-Request-Id header. If the client sends one it is preserved; otherwise a new UUID is generated.

func RequestLogger

func RequestLogger(log *logger.Logger) Middleware

RequestLogger returns middleware that logs every request with method, path, status code, and duration. Health-check paths are silently skipped.

type RateLimitConfig

type RateLimitConfig struct {
	// RequestsPerMinute is the maximum number of requests allowed per minute per key.
	RequestsPerMinute int
	// KeyFunc extracts the rate limit key from a request. Defaults to client IP.
	KeyFunc func(*gin.Context) string
}

RateLimitConfig configures the rate limiting middleware.

Jump to

Keyboard shortcuts

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