middleware

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package middleware defines a protocol-agnostic middleware abstraction that serves both HTTP (gin) and gRPC transports. A single Middleware can be applied to both through the GinHandler and UnaryServerInterceptor adapters, so cross-cutting concerns (logging, tracing, metrics, recovery, timeout) are written once and reused across protocols.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BodyLimit

func BodyLimit(maxBytes int64) gin.HandlerFunc

BodyLimit returns a gin middleware that caps the request body size. It wraps the request body with http.MaxBytesReader so reading an oversized body fails with 413 instead of buffering it unboundedly in memory.

func CORS

func CORS(cfg CORSConfig) gin.HandlerFunc

CORS returns a gin middleware implementing Cross-Origin Resource Sharing. It handles preflight OPTIONS requests and appends the relevant headers to actual responses.

func GinHandler

func GinHandler(m Middleware) gin.HandlerFunc

GinHandler bridges a unified Middleware to a gin handler. It injects a Transporter (Kind=HTTP, Operation="METHOD /path") into the request context and lets the middleware wrap the remainder of the gin chain via c.Next().

func IdentityFromContext

func IdentityFromContext(ctx context.Context) (string, bool)

IdentityFromContext returns the authenticated identity injected by Auth, and whether it was present.

func Register

func Register(name string, f Factory)

Register registers a middleware factory under name.

func Registered

func Registered(name string) bool

Registered reports whether a middleware is registered under name.

func StreamServerInterceptor

func StreamServerInterceptor(m Middleware) grpc.StreamServerInterceptor

StreamServerInterceptor bridges a unified Middleware to a gRPC server stream interceptor. The middleware's req parameter carries the server stream, so cross-cutting concerns (recovery, logging, metrics, tracing, timeout) written once against the unary Handler also wrap streaming RPCs. Business streaming handlers receive a stream whose context carries the injected Transporter.

func UnaryClientInterceptor

func UnaryClientInterceptor(m Middleware) grpc.UnaryClientInterceptor

UnaryClientInterceptor bridges a unified Middleware to a gRPC client interceptor, so the same middleware can wrap outbound calls.

func UnaryServerInterceptor

func UnaryServerInterceptor(m Middleware) grpc.UnaryServerInterceptor

UnaryServerInterceptor bridges a unified Middleware to a gRPC server interceptor. It injects a Transporter (Kind=GRPC, Operation=full method) into the context so downstream middleware can read protocol metadata.

Types

type CORSConfig

type CORSConfig struct {
	// AllowOrigins lists permitted origins. Empty means allow all ("*").
	AllowOrigins []string
	// AllowMethods lists permitted methods. Empty means a sensible default.
	AllowMethods []string
	// AllowHeaders lists permitted request headers. Empty means reflect the
	// request's Access-Control-Request-Headers.
	AllowHeaders []string
	// ExposeHeaders lists headers exposed to the browser.
	ExposeHeaders []string
	// AllowCredentials permits credentials (cookies, auth headers).
	AllowCredentials bool
	// MaxAge is the preflight cache duration in seconds.
	MaxAge int
}

CORSConfig configures CORS handling.

type Factory

type Factory func() Middleware

Factory constructs a Middleware. Registered middlewares can be referenced by name (e.g. from route-level middleware configuration).

type Handler

type Handler func(ctx context.Context, req interface{}) (interface{}, error)

Handler is the unified request handler. Its signature is identical to grpc.UnaryHandler, which is what makes the gRPC bridge a near-zero cost.

func FromGin

func FromGin(h gin.HandlerFunc) Handler

FromGin lifts a raw gin.HandlerFunc into a unified Handler, useful as the terminal node of a middleware chain.

type Middleware

type Middleware func(Handler) Handler

Middleware decorates a Handler, following the decorator and chain-of-responsibility patterns.

func Auth

func Auth(key, identityKey string) Middleware

Auth returns a middleware that verifies a Bearer JWT from the request and injects the extracted identity into the context. It is protocol-agnostic: the token is read from the Authorization header (HTTP) or the equivalent gRPC metadata via the Transporter. identityKey names the JWT claim holding the subject; key is the HMAC signing key.

Use IdentityFromContext to retrieve the identity in downstream handlers.

func Build

func Build(ctx context.Context, builders ...MiddlewareBuilder) Middleware

Build resolves builders into a single Middleware, preserving order (first builder outermost). Nil middlewares produced by a builder are skipped.

func Chain

func Chain(outer Middleware, others ...Middleware) Middleware

Chain assembles middlewares so that the first argument is the outermost (executed first) and the last is the innermost (closest to the handler).

Chain(m1, m2, m3)(h) == m1(m2(m3(h)))

func ChainSuites

func ChainSuites(suites ...Suite) Middleware

ChainSuites combines the middlewares of several suites into one, preserving suite order (the first suite's middlewares are outermost).

func Get

func Get(name string) (Middleware, error)

Get returns the middleware registered under name.

func Logging

func Logging(logger *slog.Logger) Middleware

Logging returns a middleware that logs one structured record per request, including the transport kind, operation and elapsed duration. It uses the provided logger, falling back to the global default.

func Metrics

func Metrics(meter metric.Meter) Middleware

Metrics returns a middleware that records request count, duration, in-flight gauge and error classification via OpenTelemetry metrics, tagged with transport kind and operation. Errors are tagged with their semantic Reason so alerting can aggregate on low-cardinality failure categories.

func RateLimit

func RateLimit(l ratelimit.Limiter) Middleware

RateLimit returns a middleware that drops requests when the limiter denies them, returning errno.ErrRateLimited. The limiter is transport-agnostic, so the same limiter can guard both gRPC and HTTP endpoints. When the limiter supports AllowContext, the handler's context is honored so a canceled request does not block on the backing store.

func Recovery

func Recovery() Middleware

Recovery returns a middleware that recovers from panics in downstream handlers, logs the panic with its stack trace, and converts it into a returned error so the server keeps running.

func Timeout

func Timeout(d time.Duration) Middleware

Timeout returns a middleware that imposes a per-request deadline on the downstream handler. It follows the deadline (timeout) stability pattern.

func Tracing

func Tracing(tracer trace.Tracer) Middleware

Tracing returns a middleware that starts a server span per request, named by the transport operation, and records any returned error on the span.

type MiddlewareBuilder

type MiddlewareBuilder func(ctx context.Context) Middleware

MiddlewareBuilder constructs a Middleware at run time given a context, allowing a middleware to be parameterized by values only available then (an event bus, per-service configuration, ...). It is modeled on kitex's endpoint.MiddlewareBuilder.

type Suite

type Suite interface {
	// Name returns a stable identifier for the suite.
	Name() string
	// Build returns the middlewares in outermost-first order.
	Build() []Middleware
}

Suite groups a set of related middlewares into a reusable unit, so callers can attach a coherent bundle (e.g. "observability" = logging+tracing+metrics) in one step instead of assembling the chain manually.

Directories

Path Synopsis
Package matcher provides route-level middleware selection: it maps a transport operation (gRPC full method or "METHOD /path") to the middlewares that apply to it, so different endpoints can carry different cross-cutting concerns (e.g.
Package matcher provides route-level middleware selection: it maps a transport operation (gRPC full method or "METHOD /path") to the middlewares that apply to it, so different endpoints can carry different cross-cutting concerns (e.g.

Jump to

Keyboard shortcuts

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