middleware

package
v0.1.6 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	// AuthPrincipalKey is the context key for the authenticated principal.
	AuthPrincipalKey contextKeyAuth = "auth_principal"
)
View Source
const RequestIDKey contextKey = "request_id"

RequestIDKey is the context key for the request ID.

Variables

This section is empty.

Functions

func Authenticate

func Authenticate(authSvc *service.AuthService) func(http.Handler) http.Handler

Authenticate returns an HTTP middleware that validates the request's authentication credentials. It supports two methods:

  1. API key via the X-API-Key header (for service consumers)
  2. JWT Bearer token via the Authorization header (for admin users)

On success, a Principal is attached to the request context. On failure, a 401 JSON error response is returned.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID extracts the request ID from the context. Returns an empty string if no request ID is present.

func Logger

func Logger(logger *slog.Logger) func(http.Handler) http.Handler

Logger returns an HTTP middleware that logs every request using structured logging. It captures the method, path, status code, response size, duration, request ID, and remote address.

func RateLimit

func RateLimit(requestsPerMinute int) func(http.Handler) http.Handler

RateLimit returns an HTTP middleware that limits requests per IP address to the specified number per minute. Uses a sliding window algorithm.

func RateLimitByHeader

func RateLimitByHeader(headerName string, requestsPerMinute int) func(http.Handler) http.Handler

RateLimitByHeader returns an HTTP middleware that limits requests by a specific header value (e.g., X-API-Key) to the specified number per minute. Useful for per-key rate limiting.

func RequestID

func RequestID(next http.Handler) http.Handler

RequestID is an HTTP middleware that assigns a unique UUID v7 to each request. If the client already provides an X-Request-ID header, that value is used instead. The ID is set on both the response header and the request context.

func RequireAdmin

func RequireAdmin() func(http.Handler) http.Handler

RequireAdmin returns an HTTP middleware that enforces admin-level access. It must be used after Authenticate in the middleware chain.

Types

type Principal

type Principal struct {
	Type    string // "admin" or "api_key"
	AdminID int64
	RoleID  int64
	IsAdmin bool
}

Principal represents the authenticated identity making the request.

func GetPrincipal

func GetPrincipal(ctx context.Context) *Principal

GetPrincipal extracts the authenticated principal from the context. Returns nil if no principal is present (i.e., unauthenticated request).

Jump to

Keyboard shortcuts

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