Documentation
¶
Index ¶
- Constants
- func Authenticate(authSvc *service.AuthService) func(http.Handler) http.Handler
- func GetRequestID(ctx context.Context) string
- func Logger(logger *slog.Logger) func(http.Handler) http.Handler
- func RateLimit(requestsPerMinute int) func(http.Handler) http.Handler
- func RateLimitByHeader(headerName string, requestsPerMinute int) func(http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- func RequireAdmin() func(http.Handler) http.Handler
- type Principal
Constants ¶
const (
// AuthPrincipalKey is the context key for the authenticated principal.
AuthPrincipalKey contextKeyAuth = "auth_principal"
)
const RequestIDKey contextKey = "request_id"
RequestIDKey is the context key for the request ID.
Variables ¶
This section is empty.
Functions ¶
func Authenticate ¶
Authenticate returns an HTTP middleware that validates the request's authentication credentials. It supports two methods:
- API key via the X-API-Key header (for service consumers)
- 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 ¶
GetRequestID extracts the request ID from the context. Returns an empty string if no request ID is present.
func Logger ¶
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 ¶
RateLimit returns an HTTP middleware that limits requests per IP address to the specified number per minute. Uses a sliding window algorithm.
func RateLimitByHeader ¶
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.
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 ¶
GetPrincipal extracts the authenticated principal from the context. Returns nil if no principal is present (i.e., unauthenticated request).