plugins

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package plugins provides production-ready middleware for tyche APIs — recoverer, request ID, real IP, logging, timeout, rate limiting, CORS, security headers, gzip/brotli compression, and instrumentation — applied with api.Use (handler middleware) or api.UseHTTP (edge middleware). The rate limiter returns a struct so its refill goroutine can be stopped via Stop.

Index

Constants

This section is empty.

Variables

View Source
var ErrCORSWildcardWithCredentials = errors.New("CORS: wildcard origin with AllowCredentials is invalid; credentials require specific origin")

Functions

func CORS

func CORSWithDefaults

func CORSWithDefaults() server.ServeHTTPMiddleware

func Compressor

func Compressor(cfg ...CompressorConfig) server.Middleware

func CompressorWithDefaults

func CompressorWithDefaults() server.Middleware

func Instrument

func Instrument(obs RequestObserver) server.Middleware

Instrument returns HandlerFunc middleware that records timing and the handler's returned error for each request and reports them to obs. It is dependency-free; wire obs to your telemetry backend of choice.

router.Use(plugins.Instrument(plugins.ObserverFunc(func(i plugins.RequestInfo) {
	metrics.RequestDuration.WithLabelValues(i.Method, i.Route, strconv.Itoa(i.Status)).Observe(i.Duration.Seconds())
})))

IMPORTANT: because this runs inside the router's error-handling boundary, the observed Status/Bytes reflect only what the handler itself wrote. When a handler returns an error, the router renders the response afterwards, so Status will be the handler's default (200) rather than the final status — use RequestInfo.Err to classify those. For accurate final status and bytes (including error and 404/405 responses), use InstrumentHTTP instead, which wraps the entire router.

The wrapper preserves http.Flusher, http.Hijacker, io.ReaderFrom, and http.Pusher, so it composes safely with streaming (Server-Sent Events) and WebSocket upgrade handlers.

func InstrumentHTTP

func InstrumentHTTP(obs RequestObserver) server.ServeHTTPMiddleware

InstrumentHTTP returns http.Handler middleware (for server.API.UseHTTP) that records timing, the final response status, and bytes written for every request — including responses produced by the router's error handler and the not-found / method-not-allowed handlers. It wraps the whole router, so unlike Instrument the Status is always the true status sent to the client.

It cannot observe the handler's returned Go error (the router has already converted it to a response by this layer), so RequestInfo.Err is always nil; classify failures by Status. This is the recommended seam for metrics.

router.UseHTTP(plugins.InstrumentHTTP(obs))

func Logger

func Logger(cfg ...LoggerConfig) server.Middleware

func LoggerWithDefaults

func LoggerWithDefaults(cfg ...LoggerConfig) server.Middleware

func RealIP

func RealIP(cfg ...RealIPConfig) server.Middleware

func RealIPWithDefaults

func RealIPWithDefaults() server.Middleware

func Recoverer

func Recoverer(cfg ...RecovererConfig) server.Middleware

func RecovererWithDefaults

func RecovererWithDefaults(cfg ...RecovererConfig) server.Middleware

func RequestID

func RequestID(cfg ...RequestIDConfig) server.Middleware

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

func RequestIDWithDefaults

func RequestIDWithDefaults() server.Middleware

func Security

func Security(cfg ...SecurityConfig) server.ServeHTTPMiddleware

func SecurityMiddleware

func SecurityMiddleware(cfg ...SecurityConfig) server.ServeHTTPMiddleware

func SecurityWithDefaults

func SecurityWithDefaults() server.ServeHTTPMiddleware

func Timeout

func Timeout(cfg ...TimeoutConfig) server.Middleware

func TimeoutWithDefaults

func TimeoutWithDefaults() server.Middleware

func TrailingSlash

func TrailingSlash(cfg ...TrailingSlashConfig) server.Middleware

func TrailingSlashRemove

func TrailingSlashRemove() server.Middleware

func TrailingSlashWithDefaults

func TrailingSlashWithDefaults() server.Middleware

Types

type CORSConfig

type CORSConfig struct {
	AllowOriginFunc    func(r *http.Request, origin string) bool
	AllowedOrigins     []string
	AllowedMethods     []string
	AllowedHeaders     []string
	ExposedHeaders     []string
	MaxAge             int
	AllowCredentials   bool
	OptionsPassthrough bool
}

type CompressorConfig

type CompressorConfig struct {
	ContentTypes            []string
	Level                   int
	MaxCompressedSize       int64
	MaxBufferedResponseSize int64
}

type LoggerConfig

type LoggerConfig struct {
	LogFunc     func(method, path, query string, status int, duration time.Duration, err error)
	MaxBodySize int
	WithBody    bool
	WithQuery   bool
	DurationMs  bool
}

type ObserverFunc

type ObserverFunc func(RequestInfo)

ObserverFunc adapts a plain function to a RequestObserver.

func (ObserverFunc) ObserveRequest

func (f ObserverFunc) ObserveRequest(info RequestInfo)

ObserveRequest calls f(info).

type RateLimitConfig

type RateLimitConfig struct {
	RequestsPerSecond int
	Burst             int
}

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter is a token-bucket rate limiter. Apply it as middleware with api.Use(rl.Middleware()) and call Stop when done to end its refill goroutine.

func RateLimit

func RateLimit(cfg ...RateLimitConfig) *RateLimiter

func RateLimitWithDefaults

func RateLimitWithDefaults() *RateLimiter

func (*RateLimiter) Middleware

func (m *RateLimiter) Middleware() server.Middleware

func (*RateLimiter) Stop

func (m *RateLimiter) Stop()

type RealIPConfig

type RealIPConfig struct {
	TrustedProxies []string
}

type RecovererConfig

type RecovererConfig struct {
	Logger interface{ Error(...any) }
}

type RecovererOption

type RecovererOption func(*recovererMiddleware)

type RequestIDConfig

type RequestIDConfig struct {
	HeaderName string
}

type RequestInfo

type RequestInfo struct {
	Err      error
	Method   string
	Route    string
	Path     string
	Status   int
	Bytes    int64
	Duration time.Duration
}

RequestInfo is the set of metrics captured for a single handled request. It is passed to a RequestObserver after the handler completes.

type RequestObserver

type RequestObserver interface {
	ObserveRequest(info RequestInfo)
}

RequestObserver receives a RequestInfo for every handled request. It is the integration seam for tracing and metrics backends: implement it to bridge to OpenTelemetry, Prometheus, StatsD, or any sink. Implementations must be safe for concurrent use and should not block.

type SecurityConfig

type SecurityConfig struct {
	XFrameOptions         string
	XContentTypeOptions   string
	XSSProtection         string
	ContentTypeOptions    string
	ReferrerPolicy        string
	PermissionsPolicy     string
	CrossDomainPolicy     string
	HSTSMaxAge            int
	HSTSIncludeSubdomains bool
	HSTSPreload           bool
}

type TimeoutConfig

type TimeoutConfig struct {
	Timeout        time.Duration
	HandlerTimeout time.Duration
}

type TrailingSlashConfig

type TrailingSlashConfig struct {
	Redirect bool
}

Jump to

Keyboard shortcuts

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