Documentation
¶
Overview ¶
Package middleware provides HTTP middleware for NVX applications.
Index ¶
- Variables
- func ApplyMiddleware(handler http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler
- func FullURL(r *http.Request) string
- func Heartbeat(path string) func(http.Handler) http.Handler
- func RateLimit(cfg ConfigLimiter, signatureSecret string) func(http.Handler) http.Handler
- func ReadAndRestoreBody(r *http.Request, limit int64) ([]byte, error)
- func ResolveBodyToken(contentType string, body []byte) string
- func WithActivityContext(r *http.Request) *http.Request
- type ChainConfig
- type Config
- type ConfigLimiter
- type ConsoleStore
- type LogEvent
- type LogStore
- type Logger
- type Manager
- func (m *Manager) AdminChain(cfg ChainConfig, adminCheck func(http.Handler) http.Handler) func(http.Handler) http.Handler
- func (m *Manager) CORS(next http.Handler, allowedOrigins []string, allowedHeaders []string) http.Handler
- func (m *Manager) ChiCompress(level int) func(http.Handler) http.Handler
- func (m *Manager) ChiHeartbeat(endpoint string) func(http.Handler) http.Handler
- func (m *Manager) ChiNoCache(next http.Handler) http.Handler
- func (m *Manager) ChiProfiler() http.Handler
- func (m *Manager) ChiStripSlashes(next http.Handler) http.Handler
- func (m *Manager) ChiThrottle(limit int) func(http.Handler) http.Handler
- func (m *Manager) ChiThrottleBacklog(limit int, backlog int, backlogTimeout time.Duration) func(http.Handler) http.Handler
- func (m *Manager) ChiTimeout(timeout time.Duration) func(http.Handler) http.Handler
- func (m *Manager) Config() Config
- func (m *Manager) EnsureInternal(next http.Handler) http.Handler
- func (m *Manager) EnsurePreSignHeaders(next http.Handler) http.Handler
- func (m *Manager) EnsurePublic(next http.Handler) http.Handler
- func (m *Manager) EnsurePublicAPIKey(next http.Handler) http.Handler
- func (m *Manager) EnsurePublicAuth(next http.Handler) http.Handler
- func (m *Manager) GRPCStreamInterceptor() grpc.StreamServerInterceptor
- func (m *Manager) GRPCUnaryInterceptor() grpc.UnaryServerInterceptor
- func (m *Manager) GraphQLBlockIntrospection(next http.Handler) http.Handler
- func (m *Manager) GraphQLChain(maxDepth int) func(http.Handler) http.Handler
- func (m *Manager) InternalChain(cfg ChainConfig) func(http.Handler) http.Handler
- func (m *Manager) Logger(next http.Handler) http.Handler
- func (m *Manager) MaxBodySize() func(http.Handler) http.Handler
- func (m *Manager) MethodOnly(method string, next http.Handler) http.Handler
- func (m *Manager) PreSignChain(cfg ChainConfig) func(http.Handler) http.Handler
- func (m *Manager) PreSignHandler(cfg ChainConfig) http.Handler
- func (m *Manager) PublicAPIKeyChain(cfg ChainConfig) func(http.Handler) http.Handler
- func (m *Manager) PublicAuthChain(cfg ChainConfig) func(http.Handler) http.Handler
- func (m *Manager) PublicChain(cfg ChainConfig) func(http.Handler) http.Handler
- func (m *Manager) Recoverer(next http.Handler) http.Handler
- func (m *Manager) RemoveHeaders(next http.Handler) http.Handler
- func (m *Manager) SecureHeaders(next http.Handler) http.Handler
- func (m *Manager) SetHeaderAuthType(next http.Handler, authType string) http.Handler
- func (m *Manager) TrustProxy(next http.Handler) http.Handler
- func (m *Manager) WebSocketChain(authenticator func(r *http.Request) bool) func(http.Handler) http.Handler
- func (m *Manager) WebhookChain(cfg ChainConfig) func(http.Handler) http.Handler
- func (m *Manager) WrapWithChiWriter(w http.ResponseWriter, r *http.Request) chimiddleware.WrapResponseWriter
Constants ¶
This section is empty.
Variables ¶
var ( // ErrMissingKeys is returned when PublicKeySignature or PrivateKeySignature are empty. ErrMissingKeys = fmt.Errorf("PublicKeySignature and PrivateKeySignature are required") // ErrMissingOrigins is returned when AllowedOrigins is empty. ErrMissingOrigins = fmt.Errorf("AllowedOrigins must not be empty") )
Functions ¶
func ApplyMiddleware ¶
func ApplyMiddleware(handler http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler
ApplyMiddleware applies a list of middleware to a handler. The middleware are applied in reverse order so that the first middleware in the list is the first one to process the request (outermost).
func FullURL ¶
FullURL reconstructs the full request URL, respecting X-Forwarded-Proto and X-Forwarded-Host. The scheme is restricted to http/https to prevent injection.
func RateLimit ¶
RateLimit creates a rate limiting middleware based on the provided configuration. It supports per-header keying (e.g., by IP, API Key, User ID) and custom limiter hooks. It adds standard rate limit headers to the response (X-RateLimit-Limit, etc.).
func ReadAndRestoreBody ¶
ReadAndRestoreBody reads the request body up to limit bytes and then restores it so subsequent handlers can read it again. Returns nil for nil or multipart bodies.
func ResolveBodyToken ¶
ResolveBodyToken computes a canonical body token for use in signature generation.
- Multipart bodies → "UNSIGNED"
- Empty bodies → "EMPTY"
- All others → hex-encoded SHA-256 of the raw body
Types ¶
type ChainConfig ¶
type ChainConfig struct {
// UseChiCompress enables the Chi Compress middleware for response compression.
UseChiCompress bool
// UseChiTimeout enables the Chi Timeout middleware to set a request processing timeout.
UseChiTimeout bool
// UseChiThrottle enables the Chi Throttle middleware to limit concurrent requests.
UseChiThrottle bool
// UseChiRateLimitAuth enables rate limiting for authenticated routes.
UseChiRateLimitAuth bool
// UseChiRateLimitPublic enables rate limiting for public routes.
UseChiRateLimitPublic bool
// UseChiStripSlashes enables the Chi StripSlashes middleware to handle trailing slashes.
UseChiStripSlashes bool
// CompressionLevel sets the compression level (1-9) if UseChiCompress is true.
CompressionLevel int
// ThrottleLimit sets the maximum number of concurrent requests if UseChiThrottle is true.
ThrottleLimit int
// ThrottleTimeout sets the max duration to wait for a slot if UseChiThrottle is true.
ThrottleTimeout time.Duration
// ThrottleBacklog sets the maximum size of the backlog queue for throttled requests.
ThrottleBacklog int
// LimiterConfig holds the configuration for the custom rate limiter.
LimiterConfig ConfigLimiter
}
ChainConfig configures which middleware to use in a middleware chain. It allows toggling specific Chi middleware and configuring parameters like compression, throttling, and rate limiting.
func DefaultChainConfig ¶
func DefaultChainConfig() ChainConfig
DefaultChainConfig returns a ChainConfig with recommended default values.
type Config ¶
type Config struct {
// LogStore is the storage implementation for audit logs.
LogStore LogStore
// Logger is used for internal middleware logging. Defaults to a zerolog console logger.
// Use NewZerologLogger() to wrap a *zerolog.Logger, or implement the Logger interface directly.
Logger Logger
// Env specifies the environment ("development", "production", "prod").
// Error details are suppressed in production.
Env string
// RequestTimeout is the default duration to wait for a request to complete.
RequestTimeout time.Duration
// RequestBodyLimitSize is the maximum allowed size for request bodies (including file uploads).
RequestBodyLimitSize int64
// RequestBodyNonFileLimitSize is the maximum allowed size for non-file (JSON/form) request bodies.
RequestBodyNonFileLimitSize int64
// LogRequestBodies enables capturing the request body in audit logs.
LogRequestBodies bool
// LogResponseBodies enables capturing the response body in audit logs.
LogResponseBodies bool
// ResponseBodyLogLimitSize caps the response body size (bytes) stored in audit logs.
ResponseBodyLogLimitSize int64
// PublicKeySignature is the HMAC key used for verifying public request signatures.
PublicKeySignature string
// PrivateKeySignature is the HMAC key used for verifying internal request signatures.
PrivateKeySignature string
// TrustedProxies is a list of trusted proxy IP addresses or CIDR ranges.
// The real client IP is extracted from X-Forwarded-For only when the proxy is trusted.
TrustedProxies []string
// AllowedOrigins is a list of allowed CORS origins. Use ["*"] to allow all.
AllowedOrigins []string
// AllowedContentTypes is a list of allowed Content-Type values (substring match).
AllowedContentTypes []string
// AllowedHeaders is a list of allowed CORS request headers.
AllowedHeaders []string
// HeadersToRemove is a list of response headers to strip before sending to the client.
HeadersToRemove []string
// SecurityHeaders is a map of security-related response headers to add automatically.
SecurityHeaders map[string]string
// SignatureTimestampExpired is the allowed clock skew in seconds for signature timestamp validation.
SignatureTimestampExpired int64
// RequiredPublicAuthHeaders are headers required for authenticated public requests.
RequiredPublicAuthHeaders []string
// RequiredPublicHeaders are headers required for unauthenticated public requests.
RequiredPublicHeaders []string
// RequiredInternalHeaders are headers required for internal service-to-service requests.
RequiredInternalHeaders []string
// RequiredPublicAPIKeyHeaders are headers required for API-key authenticated requests.
RequiredPublicAPIKeyHeaders []string
// RequiredSignaturePublicHeaders are the headers whose values are included in the public signature.
RequiredSignaturePublicHeaders []string
// RequiredSignatureInternalHeaders are the headers whose values are included in the internal signature.
RequiredSignatureInternalHeaders []string
// ContextInjector is an optional function to inject additional values into the request context.
ContextInjector func(r *http.Request) *http.Request
// ServiceName is the name of the service, used in log fields.
ServiceName string
}
Config holds the configuration for the middleware manager. It includes core settings, logging configuration, security parameters, and header requirements.
type ConfigLimiter ¶
type ConfigLimiter struct {
// RateLimitRequests is the number of requests allowed per window.
RateLimitRequests int
// RateLimitWindow is the duration of the rate limit window.
RateLimitWindow time.Duration
// Counter is the backend storage for the rate limiter limits (e.g., memory, redis).
Counter httprate.LimitCounter
// PreRequestOnBeforeLimiter is a hook executed before the rate limiter check.
// Return false to abort the request.
PreRequestOnBeforeLimiter func(w http.ResponseWriter, r *http.Request) bool
// PreRequestOnAfterLimiter is a hook executed after the rate limiter check but before the handler.
// Return false to abort the request.
PreRequestOnAfterLimiter func(w http.ResponseWriter, r *http.Request) bool
// LimiterHook is the rate limiter function to use.
LimiterHook func(http.Handler) http.Handler
}
ConfigLimiter holds configuration for the custom rate limiter.
type ConsoleStore ¶
type ConsoleStore struct {
// contains filtered or unexported fields
}
ConsoleStore is the default LogStore implementation that writes structured log entries to stdout via the configured Logger.
type LogEvent ¶
type LogEvent interface {
Str(key, val string) LogEvent
Err(err error) LogEvent
Interface(key string, val any) LogEvent
Msgf(format string, args ...any)
Msg(msg string)
}
LogEvent is a builder for a single log entry. It follows a fluent API pattern.
type LogStore ¶
type LogStore interface {
// Save persists an audit log entry. ctx carries request-scoped values.
Save(ctx context.Context, entry model.AuditLog) error
}
LogStore defines the interface for persisting audit log entries. Implement this to store logs in a database, message queue, or any backend.
type Logger ¶
type Logger interface {
// Error returns an event builder for error-level logging.
Error() LogEvent
// Info returns an event builder for info-level logging.
Info() LogEvent
}
Logger is the logging interface used by the middleware manager. Implement this to use a custom logging backend (e.g., slog, logrus, zap).
func NewZerologLogger ¶
NewZerologLogger wraps a *zerolog.Logger into the Logger interface.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager holds the middleware configuration and provides middleware methods. It is the central entry point for creating and managing middleware chains.
func NewWithError ¶
NewWithError creates a new Middleware Manager, returning an error instead of panicking if the configuration is invalid. Prefer this over New for production use.
func (*Manager) AdminChain ¶
func (m *Manager) AdminChain(cfg ChainConfig, adminCheck func(http.Handler) http.Handler) func(http.Handler) http.Handler
AdminChain creates a middleware chain for admin routes.
func (*Manager) CORS ¶
func (m *Manager) CORS( next http.Handler, allowedOrigins []string, allowedHeaders []string, ) http.Handler
CORS sets Cross-Origin Resource Sharing response headers. It validates the request Origin against the allowedOrigins list, handles OPTIONS preflight requests, and sets CORS headers accordingly.
func (*Manager) ChiCompress ¶
ChiCompress wraps Chi's Compress middleware. It returns a middleware that compresses the response body based on the client's Accept-Encoding header. Level is the compression level (1-9).
func (*Manager) ChiHeartbeat ¶
ChiHeartbeat wraps Chi's Heartbeat middleware. It returns a middleware that responds to a specific path with a 200 OK status.
func (*Manager) ChiNoCache ¶
ChiNoCache wraps Chi's NoCache middleware. It returns a middleware that sets headers to prevent caching of the response.
func (*Manager) ChiProfiler ¶
ChiProfiler wraps Chi's Profiler middleware. It returns a middleware that mounts pprof endpoints at /debug/pprof. This is strictly for debugging and should not be enabled in production public endpoints.
func (*Manager) ChiStripSlashes ¶
ChiStripSlashes wraps Chi's StripSlashes middleware. It returns a middleware that will match a request against a path without a trailing slash if the original request had one and no handler was found.
func (*Manager) ChiThrottle ¶
ChiThrottle wraps Chi's Throttle middleware. It returns a middleware that limits the number of concurrent requests to the handler.
func (*Manager) ChiThrottleBacklog ¶
func (m *Manager) ChiThrottleBacklog(limit int, backlog int, backlogTimeout time.Duration) func(http.Handler) http.Handler
ChiThrottleBacklog wraps Chi's ThrottleBacklog middleware. It returns a middleware that limits concurrent requests and maintains a backlog of requests waiting for a slot, with a timeout for how long they can wait in the queue.
func (*Manager) ChiTimeout ¶
ChiTimeout wraps Chi's Timeout middleware. It returns a middleware that cancels the context after the given timeout.
func (*Manager) EnsureInternal ¶
EnsureInternal validates that headers required for internal service-to-service communication are present and that the request signature is valid.
func (*Manager) EnsurePreSignHeaders ¶
EnsurePreSignHeaders validates that the headers required for presigned request generation are present.
func (*Manager) EnsurePublic ¶
EnsurePublic validates headers required for unauthenticated public requests. It checks header presence, timestamp validity, and request signature.
func (*Manager) EnsurePublicAPIKey ¶
EnsurePublicAPIKey validates headers required for API-key authenticated public requests. It checks header presence, timestamp validity, and request signature.
func (*Manager) EnsurePublicAuth ¶
EnsurePublicAuth validates headers required for authenticated public requests (e.g., a logged-in user calling a mobile app endpoint). It checks header presence, timestamp validity, and request signature.
func (*Manager) GRPCStreamInterceptor ¶
func (m *Manager) GRPCStreamInterceptor() grpc.StreamServerInterceptor
GRPCStreamInterceptor returns a gRPC stream server interceptor that provides:
- Transaction ID generation / propagation from incoming metadata
- Context enrichment (user ID, API key, IP, etc.)
- Panic recovery with structured logging
- Stream open/close latency logging
func (*Manager) GRPCUnaryInterceptor ¶
func (m *Manager) GRPCUnaryInterceptor() grpc.UnaryServerInterceptor
GRPCUnaryInterceptor returns a gRPC unary server interceptor that provides:
- Transaction ID generation / propagation from incoming metadata
- Context enrichment (user ID, API key, IP, etc.)
- Panic recovery with structured logging
- Request/response latency logging
func (*Manager) GraphQLBlockIntrospection ¶
GraphQLBlockIntrospection is a middleware that rejects GraphQL introspection queries. Useful for hardening production endpoints.
func (*Manager) GraphQLChain ¶
GraphQLChain returns a middleware chain for GraphQL endpoints.
It applies (in order, outer → inner):
- TrustProxy
- Context injection (transaction ID, user ID, etc.)
- Panic recovery
- Operation name extraction (populates r.Header "X-GraphQL-Operation")
- Query depth limiting (returns 400 if nesting depth exceeds maxDepth; 0 = unlimited)
- Structured access logging
Usage:
router.Handle("/graphql", mgr.GraphQLChain(20)(graphqlHandler))
func (*Manager) InternalChain ¶
InternalChain creates a middleware chain for internal service-to-service routes.
func (*Manager) Logger ¶
Logger logs each request and its response, capturing method, URL, status code, latency, headers, and optionally request/response bodies. Audit entries are persisted asynchronously via the configured LogStore.
func (*Manager) MaxBodySize ¶
MaxBodySize returns a middleware that enforces request body size limits and Content-Type allowlist. Different limits apply for file uploads (multipart) vs regular JSON/form requests.
func (*Manager) MethodOnly ¶
MethodOnly restricts the handler to a single HTTP method. Requests with a different method receive 405 Method Not Allowed.
func (*Manager) PreSignChain ¶
PreSignChain creates a middleware chain specifically for pre-signed requests.
func (*Manager) PreSignHandler ¶
func (m *Manager) PreSignHandler(cfg ChainConfig) http.Handler
PreSignHandler creates a POST endpoint that generates a presigned signature for a described request. The caller supplies method, URI, and body hash; the handler returns the HMAC signature the caller should include as NVX-Signature.
func (*Manager) PublicAPIKeyChain ¶
PublicAPIKeyChain creates a middleware chain for public routes using API Key authentication.
func (*Manager) PublicAuthChain ¶
PublicAuthChain creates a middleware chain for public routes that require authentication.
func (*Manager) PublicChain ¶
PublicChain creates a middleware chain for public routes that do not require user authentication. Execution Order: TrustProxy -> EnsurePublic -> RateLimit -> Logger -> App
func (*Manager) Recoverer ¶
Recoverer recovers from panics, logs the panic with a stack trace, and returns HTTP 500 if a response has not yet been written.
func (*Manager) RemoveHeaders ¶
RemoveHeaders strips configured response headers before the response reaches the client. Useful for removing Server, X-Powered-By, and similar fingerprinting headers.
func (*Manager) SecureHeaders ¶
SecureHeaders adds a configured set of security-related response headers (e.g., X-Content-Type-Options, X-Frame-Options, HSTS).
func (*Manager) SetHeaderAuthType ¶
SetHeaderAuthType sets the NVX-Auth-Type header to identify the authentication context.
func (*Manager) TrustProxy ¶
TrustProxy extracts the real client IP from X-Forwarded-For when the direct connection comes from a configured trusted proxy (IP or CIDR). It updates r.RemoteAddr and sets the NVX-IP header so downstream handlers see the real client address.
func (*Manager) WebSocketChain ¶
func (m *Manager) WebSocketChain( authenticator func(r *http.Request) bool, ) func(http.Handler) http.Handler
WebSocketChain returns a middleware chain designed for WebSocket upgrade endpoints.
It applies:
- TrustProxy (real IP extraction)
- Context injection (transaction ID, user ID, etc.)
- Panic recovery (before the upgrade)
- Request logging (logs the upgrade attempt and outcome)
- Optional per-connection auth via the provided authenticator.
The authenticator receives the request before the upgrade. Return false to reject the connection (a 401 response is written automatically).
func (*Manager) WebhookChain ¶
WebhookChain creates a middleware chain specialized for handling webhooks.
func (*Manager) WrapWithChiWriter ¶
func (m *Manager) WrapWithChiWriter(w http.ResponseWriter, r *http.Request) chimiddleware.WrapResponseWriter
WrapWithChiWriter wraps a standard http.ResponseWriter with Chi's WrapResponseWriter. This provides additional functionality like capturing the status code and bytes written, which is useful for logging and other middleware that need to inspect the response.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package constants provides common constants used throughout the NVX middleware.
|
Package constants provides common constants used throughout the NVX middleware. |
|
examples
|
|
|
advanced
command
Main
|
Main |
|
basic
command
main
|
main |
|
Package model provides data structures for the middleware.
|
Package model provides data structures for the middleware. |