middleware

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package middleware provides a collection of HTTP middleware components for the SRouter framework.

Package middleware provides a collection of HTTP middleware components for the SRouter framework. These middleware components can be used to add functionality such as logging, recovery from panics, authentication, request timeouts, and more to your HTTP handlers.

Package middleware provides a collection of HTTP middleware components for the SRouter framework.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Authentication

func Authentication(authFunc func(*http.Request) bool) common.Middleware

Authentication is a middleware that checks if a request is authenticated using a simple auth function. This is a convenience wrapper around AuthenticationWithProvider for backward compatibility. It allows for custom authentication logic to be provided as a simple function.

func AuthenticationWithProvider

func AuthenticationWithProvider(provider AuthProvider, logger *zap.Logger) common.Middleware

AuthenticationWithProvider is a middleware that checks if a request is authenticated using the provided auth provider. If authentication fails, it returns a 401 Unauthorized response. This middleware allows for flexible authentication mechanisms by accepting any AuthProvider implementation.

func NewAPIKeyMiddleware

func NewAPIKeyMiddleware(validKeys map[string]bool, header, query string, logger *zap.Logger) common.Middleware

NewAPIKeyMiddleware creates a middleware that uses API Key Authentication. It takes a map of valid API keys, the header and query parameter names to check, and a logger for authentication failures.

func NewBasicAuthMiddleware

func NewBasicAuthMiddleware(credentials map[string]string, logger *zap.Logger) common.Middleware

NewBasicAuthMiddleware creates a middleware that uses HTTP Basic Authentication. It takes a map of username to password credentials and a logger for authentication failures.

func NewBearerTokenMiddleware

func NewBearerTokenMiddleware(validTokens map[string]bool, logger *zap.Logger) common.Middleware

NewBearerTokenMiddleware creates a middleware that uses Bearer Token Authentication. It takes a map of valid tokens and a logger for authentication failures.

func NewBearerTokenValidatorMiddleware

func NewBearerTokenValidatorMiddleware(validator func(string) bool, logger *zap.Logger) common.Middleware

NewBearerTokenValidatorMiddleware creates a middleware that uses Bearer Token Authentication with a custom validator function. This allows for more complex token validation logic, such as JWT validation or integration with external authentication services.

func PrometheusHandler

func PrometheusHandler(registry interface{}) http.Handler

PrometheusHandler returns an HTTP handler for exposing Prometheus metrics. This handler would typically be mounted at a path like "/metrics" to allow Prometheus to scrape the metrics. This is a placeholder implementation that doesn't actually expose real metrics.

Types

type APIKeyProvider

type APIKeyProvider struct {
	ValidKeys map[string]bool // key -> valid
	Header    string          // header name (e.g., "X-API-Key")
	Query     string          // query parameter name (e.g., "api_key")
}

APIKeyProvider provides API Key Authentication. It can validate API keys provided in a header or query parameter.

func (*APIKeyProvider) Authenticate

func (p *APIKeyProvider) Authenticate(r *http.Request) bool

Authenticate authenticates a request using API Key Authentication. It checks for the API key in either the specified header or query parameter and validates it against the stored valid keys. Returns true if authentication is successful, false otherwise.

type AuthProvider

type AuthProvider interface {
	// Authenticate authenticates a request and returns true if authentication is successful.
	// It examines the request for authentication credentials (such as headers, cookies, or query parameters)
	// and validates them according to the provider's implementation.
	// Returns true if the request is authenticated, false otherwise.
	Authenticate(r *http.Request) bool
}

AuthProvider defines an interface for authentication providers. Different authentication mechanisms can implement this interface to be used with the AuthenticationWithProvider middleware. The framework includes several implementations: BasicAuthProvider, BearerTokenProvider, and APIKeyProvider.

type BasicAuthProvider

type BasicAuthProvider struct {
	Credentials map[string]string // username -> password
}

BasicAuthProvider provides HTTP Basic Authentication. It validates username and password credentials against a predefined map.

func (*BasicAuthProvider) Authenticate

func (p *BasicAuthProvider) Authenticate(r *http.Request) bool

Authenticate authenticates a request using HTTP Basic Authentication. It extracts the username and password from the Authorization header and validates them against the stored credentials. Returns true if authentication is successful, false otherwise.

type BearerTokenProvider

type BearerTokenProvider struct {
	ValidTokens map[string]bool         // token -> valid
	Validator   func(token string) bool // optional token validator
}

BearerTokenProvider provides Bearer Token Authentication. It can validate tokens against a predefined map or using a custom validator function.

func (*BearerTokenProvider) Authenticate

func (p *BearerTokenProvider) Authenticate(r *http.Request) bool

Authenticate authenticates a request using Bearer Token Authentication. It extracts the token from the Authorization header and validates it using either the validator function (if provided) or the ValidTokens map. Returns true if authentication is successful, false otherwise.

type Middleware

type Middleware = common.Middleware

Middleware is an alias for the common.Middleware type. It represents a function that wraps an http.Handler to provide additional functionality.

func CORS

func CORS(origins []string, methods []string, headers []string) Middleware

CORS is a middleware that adds Cross-Origin Resource Sharing (CORS) headers to the response. It allows you to specify which origins, methods, and headers are allowed for cross-origin requests. This middleware also handles preflight OPTIONS requests automatically.

func Chain

func Chain(middlewares ...Middleware) Middleware

Chain chains multiple middlewares together into a single middleware. The middlewares are applied in reverse order, so the first middleware in the list will be the outermost wrapper (the first to process the request and the last to process the response).

func Logging

func Logging(logger *zap.Logger) Middleware

Logging is a middleware that logs HTTP requests and responses. It captures the request method, path, status code, and duration. The log level is determined by the status code and duration: - 500+ status codes are logged at Error level - 400-499 status codes are logged at Warn level - Requests taking longer than 1 second are logged at Warn level - All other requests are logged at Debug level

func MaxBodySize

func MaxBodySize(maxSize int64) Middleware

MaxBodySize is a middleware that limits the size of the request body. It prevents clients from sending excessively large requests that could consume too much memory or cause denial of service.

func PrometheusMetrics

func PrometheusMetrics(registry interface{}, namespace, subsystem string, enableLatency, enableThroughput, enableQPS, enableErrors bool) Middleware

PrometheusMetrics is a middleware that collects Prometheus metrics for HTTP requests. It can track request latency, throughput, queries per second, and error rates. This is a placeholder implementation that demonstrates the structure but doesn't actually record metrics to Prometheus. In a real implementation, you would use the prometheus client library.

func Recovery

func Recovery(logger *zap.Logger) Middleware

Recovery is a middleware that recovers from panics in HTTP handlers. It logs the panic and stack trace using the provided logger and returns a 500 Internal Server Error response. This prevents the server from crashing when a panic occurs in a handler.

func Timeout

func Timeout(timeout time.Duration) Middleware

Timeout is a middleware that sets a timeout for the request processing. If the handler takes longer than the specified timeout to respond, the middleware will cancel the request context and return a 408 Request Timeout response. This prevents long-running requests from blocking server resources indefinitely.

Jump to

Keyboard shortcuts

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