middleware

package module
v0.0.0-...-aecbad0 Latest Latest
Warning

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

Go to latest
Published: May 30, 2026 License: Apache-2.0 Imports: 30 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

NVX Go Middleware

A high-performance, modular, and secure HTTP middleware library for Go. Designed to be Production-Ready and DDoS-Resistant from day one. Perfect for building secure APIs with net/http, integrating seamlessly with Chi, gRPC, and WebSockets.

🚀 Features

  • ✅ High-Performance JSON - Powered by bytedance/sonic for ultra-fast request/response parsing.
  • ✅ Smart Execution Chain - DDoS & Bad Auth requests are blocked before hitting the logger or application, saving CPU & DB I/O.
  • ✅ Secure IP Resolution (TrustProxy) - Anti-spoofing mechanism for X-Forwarded-For, totally immune to arbitrary header injection.
  • ✅ OOM Guard (MaxBytesReader) - Safely caps request memory allocations before processing.
  • ✅ Rate Limiting - Dynamic per-route throttling based on verified IP or Auth Tokens.
  • ✅ Panic Recovery - Graceful recovery that logs the stack trace without leaking it to the client.
  • ✅ Audit Logging - Asynchronous database-agnostic request/response logging.
  • ✅ Multi-Protocol Support - Native wrappers for HTTP, gRPC (Unary & Stream), and WebSockets.
  • ✅ Multi-Auth Pipelines - Pre-built chains for Public, Auth, API Key, Internal, and Webhook endpoints.
  • ✅ CORS & Security Headers - Secure defaults for browser security.

📦 Installation

go get github.com/Jkenyut/nvx-go-middleware

🎯 Quick Start

package main

import (
    "log"
    "net/http"
    "time"
    
    mw "github.com/Jkenyut/nvx-go-middleware"
)

func main() {
    // 1. Create middleware manager safely
    mgr, err := mw.NewWithError(mw.Config{
        PublicKeySignature:  "your-rsa-public-key",
        PrivateKeySignature: "your-rsa-private-key",
        AllowedOrigins:      []string{"https://example.com"},
        TrustedProxies:      []string{"10.0.0.0/8"}, // Vital for accurate Rate Limits!
        RequestTimeout:      60 * time.Second,
        Env:                 "production",
    })
    if err != nil {
        log.Fatalf("Failed to init middleware: %v", err)
    }

    // 2. Load default chain behavior
    chainCfg := mw.DefaultChainConfig()
    chainCfg.UseChiRateLimitPublic = true // Enable Anti-DDoS

    mux := http.NewServeMux()

    // 3. Public Route (Rate Limited, Validated, IP Verified)
    mux.Handle("/api/v1/register", mgr.PublicChain(chainCfg)(
        mgr.MethodOnly("POST", http.HandlerFunc(registerHandler)),
    ))

    // 4. Authenticated Route (JWT + Signature)
    mux.Handle("/api/v1/profile", mgr.PublicAuthChain(chainCfg)(
        mgr.MethodOnly("GET", http.HandlerFunc(profileHandler)),
    ))

    log.Println("Server running on :8080")
    http.ListenAndServe(":8080", mux)
}

func registerHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(`{"message": "Registered"}`))
}
func profileHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(`{"message": "Profile"}`))
}

🛡️ Smart Architecture (Execution Order)

NVX Go Middleware uses a mathematically structured chain to protect your application:

  1. Outer Layer (Network): CORS and Panic Recovery.
  2. IP Resolution (TrustProxy): Extracts the real IP only if the request comes from your TrustedProxies.
  3. Validation (EnsureAuth): Drops invalid signatures/keys with 401 Unauthorized.
  4. Anti-DDoS (RateLimit): Drops excessive requests with 429 Too Many Requests.
  5. Inner Layer (Logger): Logs the request. (Because it sits inside the rate limiter, DDoS floods will NEVER pollute your database logs!)
  6. App Layer: Your business logic.

🔗 Pre-Built Middleware Chains

Depending on your endpoint's purpose, use one of our optimized chains:

  • mgr.PublicChain(): Unauthenticated users (Device validation & IP Rate limits).
  • mgr.PublicAuthChain(): Authenticated users (Requires JWT/Tokens).
  • mgr.PublicAPIKeyChain(): Server-to-Server external (Requires API Key).
  • mgr.InternalChain(): Internal microservices (Bypasses rate limits, requires strict internal keys).
  • mgr.WebhookChain(): Stripped down chain optimized for massive payload ingestion.
  • mgr.WebSocketChain(): Handles Protocol Upgrades safely.

🛠 Advanced Configuration

chainCfg := mw.ChainConfig{
    UseChiCompress:        true,  // Gzip compression
    UseChiTimeout:         true,  // Context cancellation on timeout
    UseChiThrottle:        true,  // Concurrent request limits
    UseChiStripSlashes:    true,  // Normalize URLs
    UseChiRateLimitPublic: true,  // Prevent abuse on public endpoints
    CompressionLevel:      5,
    ThrottleLimit:         100,
    LimiterConfig: mw.ConfigLimiter{
        RateLimitRequests: 30,
        RateLimitWindow:   1 * time.Minute,
    },
}

(Note: ChiRealIP was intentionally removed from this library to prevent X-Forwarded-For spoofing attacks. The library uses the superior TrustProxy algorithm automatically).

🔌 gRPC & WebSockets Integration

This middleware isn't just for REST!

gRPC Interceptors:

server := grpc.NewServer(
    grpc.ChainUnaryInterceptor(
        mgr.UnaryInterceptorPanicRecover(),
        mgr.UnaryInterceptorLogger(),
    ),
    grpc.ChainStreamInterceptor(
        mgr.StreamInterceptorPanicRecover(),
        mgr.StreamInterceptorLogger(),
    ),
)

WebSockets:

authCheck := func(r *http.Request) bool {
    return r.Header.Get("Authorization") != ""
}
mux.Handle("/ws", mgr.WebSocketChain(authCheck)(wsHandler))

📊 Custom Audit Storage

Inject your own database logger natively:

type DatabaseStore struct { db *sql.DB }

func (d *DatabaseStore) Save(ctx context.Context, entry model.AuditLog) error {
    // This executes asynchronously in a goroutine
    _, err := d.db.ExecContext(ctx, "INSERT INTO audit_logs ...")
    return err
}

mgr, _ := mw.NewWithError(mw.Config{
    LogStore: &DatabaseStore{db: myDB},
    // ...
})

📄 License

Apache 2.0 License - see LICENSE file for details.

Documentation

Overview

Package middleware provides HTTP middleware for NVX applications.

Index

Constants

This section is empty.

Variables

View Source
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

func FullURL(r *http.Request) string

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 Heartbeat

func Heartbeat(path string) func(http.Handler) http.Handler

Heartbeat returns a handler that responds to the given path with 200 OK "OK".

func RateLimit

func RateLimit(
	cfg ConfigLimiter,
	signatureSecret string,
) func(http.Handler) http.Handler

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

func ReadAndRestoreBody(r *http.Request, limit int64) ([]byte, error)

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

func ResolveBodyToken(contentType string, body []byte) string

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

func WithActivityContext

func WithActivityContext(r *http.Request) *http.Request

WithActivityContext injects standard NVX context values from request headers. Exported so protocol-specific adapters (WebSocket, gRPC) can reuse it.

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.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that required Config fields are present.

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.

func (*ConsoleStore) Save

func (c *ConsoleStore) Save(_ context.Context, entry model.AuditLog) error

Save writes the audit log entry to 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

func NewZerologLogger(l *zerolog.Logger) Logger

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

func NewWithError(cfg Config) (*Manager, error)

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

func (m *Manager) ChiCompress(level int) func(http.Handler) http.Handler

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

func (m *Manager) ChiHeartbeat(endpoint string) func(http.Handler) http.Handler

ChiHeartbeat wraps Chi's Heartbeat middleware. It returns a middleware that responds to a specific path with a 200 OK status.

func (*Manager) ChiNoCache

func (m *Manager) ChiNoCache(next http.Handler) http.Handler

ChiNoCache wraps Chi's NoCache middleware. It returns a middleware that sets headers to prevent caching of the response.

func (*Manager) ChiProfiler

func (m *Manager) ChiProfiler() http.Handler

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

func (m *Manager) ChiStripSlashes(next http.Handler) http.Handler

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

func (m *Manager) ChiThrottle(limit int) func(http.Handler) http.Handler

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

func (m *Manager) ChiTimeout(timeout time.Duration) func(http.Handler) http.Handler

ChiTimeout wraps Chi's Timeout middleware. It returns a middleware that cancels the context after the given timeout.

func (*Manager) Config

func (m *Manager) Config() Config

Config returns a copy of the manager's configuration.

func (*Manager) EnsureInternal

func (m *Manager) EnsureInternal(next http.Handler) http.Handler

EnsureInternal validates that headers required for internal service-to-service communication are present and that the request signature is valid.

func (*Manager) EnsurePreSignHeaders

func (m *Manager) EnsurePreSignHeaders(next http.Handler) http.Handler

EnsurePreSignHeaders validates that the headers required for presigned request generation are present.

func (*Manager) EnsurePublic

func (m *Manager) EnsurePublic(next http.Handler) http.Handler

EnsurePublic validates headers required for unauthenticated public requests. It checks header presence, timestamp validity, and request signature.

func (*Manager) EnsurePublicAPIKey

func (m *Manager) EnsurePublicAPIKey(next http.Handler) http.Handler

EnsurePublicAPIKey validates headers required for API-key authenticated public requests. It checks header presence, timestamp validity, and request signature.

func (*Manager) EnsurePublicAuth

func (m *Manager) EnsurePublicAuth(next http.Handler) http.Handler

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

func (m *Manager) GraphQLBlockIntrospection(next http.Handler) http.Handler

GraphQLBlockIntrospection is a middleware that rejects GraphQL introspection queries. Useful for hardening production endpoints.

func (*Manager) GraphQLChain

func (m *Manager) GraphQLChain(maxDepth int) func(http.Handler) http.Handler

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

func (m *Manager) InternalChain(cfg ChainConfig) func(http.Handler) http.Handler

InternalChain creates a middleware chain for internal service-to-service routes.

func (*Manager) Logger

func (m *Manager) Logger(next http.Handler) http.Handler

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

func (m *Manager) MaxBodySize() func(http.Handler) http.Handler

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

func (m *Manager) MethodOnly(method string, next http.Handler) http.Handler

MethodOnly restricts the handler to a single HTTP method. Requests with a different method receive 405 Method Not Allowed.

func (*Manager) PreSignChain

func (m *Manager) PreSignChain(cfg ChainConfig) func(http.Handler) http.Handler

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

func (m *Manager) PublicAPIKeyChain(cfg ChainConfig) func(http.Handler) http.Handler

PublicAPIKeyChain creates a middleware chain for public routes using API Key authentication.

func (*Manager) PublicAuthChain

func (m *Manager) PublicAuthChain(cfg ChainConfig) func(http.Handler) http.Handler

PublicAuthChain creates a middleware chain for public routes that require authentication.

func (*Manager) PublicChain

func (m *Manager) PublicChain(cfg ChainConfig) func(http.Handler) http.Handler

PublicChain creates a middleware chain for public routes that do not require user authentication. Execution Order: TrustProxy -> EnsurePublic -> RateLimit -> Logger -> App

func (*Manager) Recoverer

func (m *Manager) Recoverer(next http.Handler) http.Handler

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

func (m *Manager) RemoveHeaders(next http.Handler) http.Handler

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

func (m *Manager) SecureHeaders(next http.Handler) http.Handler

SecureHeaders adds a configured set of security-related response headers (e.g., X-Content-Type-Options, X-Frame-Options, HSTS).

func (*Manager) SetHeaderAuthType

func (m *Manager) SetHeaderAuthType(next http.Handler, authType string) http.Handler

SetHeaderAuthType sets the NVX-Auth-Type header to identify the authentication context.

func (*Manager) TrustProxy

func (m *Manager) TrustProxy(next http.Handler) http.Handler

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

func (m *Manager) WebhookChain(cfg ChainConfig) func(http.Handler) http.Handler

WebhookChain creates a middleware chain specialized for handling webhooks.

func (*Manager) WrapWithChiWriter

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.

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.

Jump to

Keyboard shortcuts

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