Documentation
¶
Overview ¶
Package middleware provides gpp HTTP middleware for security, observability, recovery, request IDs, timeouts, rate limiting, idempotency, and protocol endpoints. Process-local stores do not coordinate multiple instances.
Index ¶
- Constants
- Variables
- func CORS(configs ...CORSConfig) gpp.HandlerFunc
- func GRPCMultiplex(grpcHandler http.Handler) gpp.HandlerFunc
- func GraphQLHandler(resolver GraphQLResolver) gpp.HandlerFunc
- func GraphQLPlayground(endpoint string) gpp.HandlerFunc
- func Idempotency(cfg ...IdempotencyConfig) gpp.HandlerFunc
- func IsGRPC(r *http.Request) bool
- func Logger() gpp.HandlerFunc
- func Observability() gpp.HandlerFunc
- func Prometheus() gpp.HandlerFunc
- func RateLimit(config RateLimiterConfig) gpp.HandlerFunc
- func Recovery() gpp.HandlerFunc
- func RequestID() gpp.HandlerFunc
- func Security(configs ...SecurityConfig) gpp.HandlerFunc
- func Singleflight(configs ...SingleflightConfig) gpp.HandlerFunc
- func SwaggerUI(specJSON string) gpp.HandlerFunc
- func SystemTimeNowNano() int64
- func Timeout(duration time.Duration) gpp.HandlerFunc
- type CORSConfig
- type GraphQLRequest
- type GraphQLResolver
- type IdempotencyClaim
- type IdempotencyConfig
- type IdempotencyResponse
- type IdempotencyState
- type IdempotencyStore
- type MemoryIdempotencyStore
- func (s *MemoryIdempotencyStore) Claim(ctx context.Context, key, fingerprint, owner string, ttl time.Duration) (IdempotencyClaim, error)
- func (s *MemoryIdempotencyStore) Complete(ctx context.Context, key, fingerprint, owner string, ...) error
- func (s *MemoryIdempotencyStore) Release(ctx context.Context, key, owner string) error
- type RateLimiterConfig
- type RedisIdempotencyConfig
- type RedisIdempotencyStore
- func (s *RedisIdempotencyStore) Claim(ctx context.Context, key, fingerprint, owner string, ttl time.Duration) (IdempotencyClaim, error)
- func (s *RedisIdempotencyStore) Complete(ctx context.Context, key, fingerprint, owner string, ...) error
- func (s *RedisIdempotencyStore) Release(ctx context.Context, key, owner string) error
- type SecurityConfig
- type SingleflightConfig
Constants ¶
const ContextRequestIDKey = "request_id"
ContextRequestIDKey is the gpp context key containing the validated request ID.
const IdempotencyHeader = "Idempotency-Key"
IdempotencyHeader is the request header containing the application idempotency key.
const RequestIDHeader = "X-Request-ID"
RequestIDHeader is the HTTP request correlation header.
Variables ¶
var ( // ErrIdempotencyStoreCapacity indicates that no safe process-local entry can be admitted. ErrIdempotencyStoreCapacity = errors.New("idempotency store capacity reached") // ErrIdempotencyOwnershipLost indicates that a claim is absent, complete, or owned elsewhere. ErrIdempotencyOwnershipLost = errors.New("idempotency claim ownership lost") )
Functions ¶
func CORS ¶
func CORS(configs ...CORSConfig) gpp.HandlerFunc
CORS returns middleware that manages CORS headers and preflight OPTIONS requests.
func GRPCMultiplex ¶
func GRPCMultiplex(grpcHandler http.Handler) gpp.HandlerFunc
GRPCMultiplex returns middleware that multiplexes incoming gRPC calls to a gRPC server handler over HTTP/2.
func GraphQLHandler ¶
func GraphQLHandler(resolver GraphQLResolver) gpp.HandlerFunc
GraphQLHandler executes GraphQL query requests and returns JSON responses.
func GraphQLPlayground ¶
func GraphQLPlayground(endpoint string) gpp.HandlerFunc
GraphQLPlayground serves an interactive GraphQL Playground IDE web interface.
func Idempotency ¶
func Idempotency(cfg ...IdempotencyConfig) gpp.HandlerFunc
Idempotency returns middleware caching and replaying responses for requests with an Idempotency-Key header.
func IsGRPC ¶
IsGRPC checks whether an incoming request is a gRPC request based on Content-Type header and protocol.
func Logger ¶
func Logger() gpp.HandlerFunc
Logger creates a structured request logger middleware using stdlib slog.
func Observability ¶
func Observability() gpp.HandlerFunc
Observability returns middleware that records Prometheus request counters, active connection gauges, and latency metrics.
func Prometheus ¶
func Prometheus() gpp.HandlerFunc
Prometheus returns a HandlerFunc that serves Prometheus metrics output on /metrics.
func RateLimit ¶
func RateLimit(config RateLimiterConfig) gpp.HandlerFunc
RateLimit returns a thread-safe token bucket rate limiting middleware by client IP address.
func Recovery ¶
func Recovery() gpp.HandlerFunc
Recovery returns a panic recovery middleware that catches unexpected runtime panics.
func RequestID ¶
func RequestID() gpp.HandlerFunc
RequestID returns middleware that generates or propagates X-Request-ID HTTP headers across requests and context.
func Security ¶
func Security(configs ...SecurityConfig) gpp.HandlerFunc
Security returns middleware that applies HTTP security headers to all responses.
func Singleflight ¶
func Singleflight(configs ...SingleflightConfig) gpp.HandlerFunc
Singleflight deduplicates concurrent equivalent GET and HEAD requests within one application process. Unsafe, failed, private, and oversized responses are never replayed.
func SwaggerUI ¶
func SwaggerUI(specJSON string) gpp.HandlerFunc
SwaggerUI returns a HandlerFunc that serves an interactive Swagger UI web interface for OpenAPI specs.
func SystemTimeNowNano ¶
func SystemTimeNowNano() int64
SystemTimeNowNano is retained for source compatibility.
Types ¶
type CORSConfig ¶
type CORSConfig struct {
AllowOrigins []string
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAge string
}
CORSConfig defines configuration settings for Cross-Origin Resource Sharing.
func DefaultCORSConfig ¶
func DefaultCORSConfig() CORSConfig
DefaultCORSConfig returns standard permissive default CORS settings.
type GraphQLRequest ¶
type GraphQLRequest struct {
Query string `json:"query"`
OperationName string `json:"operationName,omitempty"`
Variables map[string]any `json:"variables,omitempty"`
}
GraphQLRequest payload representing incoming GraphQL requests.
type GraphQLResolver ¶
GraphQLResolver defines the contract for resolving GraphQL query and mutation requests.
type IdempotencyClaim ¶
type IdempotencyClaim struct {
Acquired bool
State IdempotencyState
Fingerprint string
Response *IdempotencyResponse
}
IdempotencyClaim describes either a newly acquired claim or existing state.
type IdempotencyConfig ¶
type IdempotencyConfig struct {
TTL time.Duration // Cached response lifetime; defaults to 24 hours.
PendingTTL time.Duration // In-flight claim lifetime; defaults to 30 seconds.
PendingPoll time.Duration // Distributed claim poll interval; defaults to 25 milliseconds.
MaxEntries int // Maximum completed responses retained; defaults to 10,000.
MaxKeyBytes int // Maximum Idempotency-Key size; defaults to 256 bytes.
MaxRequestBytes int64 // Maximum request body fingerprinted; defaults to 1 MiB.
MaxResponseBytes int // Maximum response body cached; defaults to 1 MiB.
Scope func(*gpp.Context) string // Optional tenant/principal scope; defaults to tenant_id and sub.
Store IdempotencyStore // Optional distributed store; defaults to bounded process memory.
}
IdempotencyConfig defines replay limits, scoping, lifetimes, and storage.
type IdempotencyResponse ¶
type IdempotencyResponse struct {
Status int `json:"status"`
Header http.Header `json:"header"`
Body []byte `json:"body"`
}
IdempotencyResponse is the replayable HTTP response persisted by a store.
type IdempotencyState ¶
type IdempotencyState string
IdempotencyState identifies whether a claim is pending or replayable.
const ( // IdempotencyPending identifies an in-flight request claim. IdempotencyPending IdempotencyState = "pending" // IdempotencyComplete identifies a stored replayable response. IdempotencyComplete IdempotencyState = "complete" )
type IdempotencyStore ¶
type IdempotencyStore interface {
Claim(ctx context.Context, key, fingerprint, owner string, ttl time.Duration) (IdempotencyClaim, error)
Complete(ctx context.Context, key, fingerprint, owner string, response IdempotencyResponse, ttl time.Duration) error
Release(ctx context.Context, key, owner string) error
}
IdempotencyStore atomically coordinates claims across middleware instances.
type MemoryIdempotencyStore ¶
type MemoryIdempotencyStore struct {
// contains filtered or unexported fields
}
MemoryIdempotencyStore is a bounded process-local implementation.
func NewMemoryIdempotencyStore ¶
func NewMemoryIdempotencyStore(maxEntries int) *MemoryIdempotencyStore
NewMemoryIdempotencyStore creates a bounded process-local idempotency store.
func (*MemoryIdempotencyStore) Claim ¶
func (s *MemoryIdempotencyStore) Claim( ctx context.Context, key, fingerprint, owner string, ttl time.Duration, ) (IdempotencyClaim, error)
Claim atomically acquires or reads a process-local idempotency record.
func (*MemoryIdempotencyStore) Complete ¶
func (s *MemoryIdempotencyStore) Complete( ctx context.Context, key, fingerprint, owner string, response IdempotencyResponse, ttl time.Duration, ) error
Complete stores a replayable response when owner still holds the pending claim.
type RateLimiterConfig ¶
type RateLimiterConfig struct {
Rate float64 // Tokens added per second
Capacity float64 // Maximum token bucket capacity
CleanupInterval time.Duration // Interval to clean inactive client buckets
MaxClients int // Maximum number of client buckets retained in memory
}
RateLimiterConfig defines rate limiting capacity and refill parameters.
type RedisIdempotencyConfig ¶
RedisIdempotencyConfig defines key namespacing and optimistic retry bounds.
type RedisIdempotencyStore ¶
type RedisIdempotencyStore struct {
// contains filtered or unexported fields
}
RedisIdempotencyStore coordinates idempotency across application instances.
func NewRedisIdempotencyStore ¶
func NewRedisIdempotencyStore(client redis.UniversalClient, config RedisIdempotencyConfig) (*RedisIdempotencyStore, error)
NewRedisIdempotencyStore validates and wraps an application-owned Redis client.
func (*RedisIdempotencyStore) Claim ¶
func (s *RedisIdempotencyStore) Claim( ctx context.Context, key, fingerprint, owner string, ttl time.Duration, ) (IdempotencyClaim, error)
Claim atomically acquires or reads an idempotency record.
func (*RedisIdempotencyStore) Complete ¶
func (s *RedisIdempotencyStore) Complete( ctx context.Context, key, fingerprint, owner string, response IdempotencyResponse, ttl time.Duration, ) error
Complete stores a replayable response when owner still holds the pending claim.
type SecurityConfig ¶
type SecurityConfig struct {
XFrameOptions string
XContentTypeOptions string
XXSSProtection string
HSTSMaxAge string
ContentSecurityPolicy string
ReferrerPolicy string
}
SecurityConfig holds configuration options for HTTP security headers.
func DefaultSecurityConfig ¶
func DefaultSecurityConfig() SecurityConfig
DefaultSecurityConfig returns OWASP recommended default security headers.
type SingleflightConfig ¶
type SingleflightConfig struct {
MaxResponseBytes int // Maximum replayable body; defaults to 1 MiB.
Scope func(*gpp.Context) string // Optional additional application-specific scope.
VaryHeaders []string // Additional request headers included in the flight key.
}
SingleflightConfig defines response bounds and request-key variation.