middleware

package
v2.1.93 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package middleware provides HTTP middleware for connexions services.

Index

Constants

View Source
const (
	ResponseHeaderSourceUpstream  = "upstream"
	ResponseHeaderSourceCache     = "cache"
	ResponseHeaderSourceGenerated = "generated"
	ResponseHeaderSourceReplay    = "replay"
)

ResponseHeaderSource values.

View Source
const ResponseHeaderRequestID = "X-Cxs-Request-Id"

ResponseHeaderRequestID is the response header containing the request ID.

View Source
const ResponseHeaderSource = "X-Cxs-Source"

ResponseHeaderSource is the response header indicating where the response came from.

Variables

This section is empty.

Functions

func AddSkipPrefix

func AddSkipPrefix(prefix string)

AddSkipPrefix adds a path prefix to the logger skip list. Requests whose path starts with this prefix will not be logged.

func CreateCacheReadMiddleware

func CreateCacheReadMiddleware(params *Params) func(http.Handler) http.Handler

CreateCacheReadMiddleware returns a middleware that checks if GET request is cached in History.

func CreateCacheWriteMiddleware

func CreateCacheWriteMiddleware(params *Params) func(http.Handler) http.Handler

CreateCacheWriteMiddleware is a method on the Router to create a middleware

func CreateConfigOverrideMiddleware

func CreateConfigOverrideMiddleware(params *Params) func(http.Handler) http.Handler

CreateConfigOverrideMiddleware creates a middleware that reads X-Cxs-* headers and temporarily overrides ServiceConfig values for the current request. Headers are case-insensitive. The original config is restored after the request completes.

func CreateLatencyAndErrorMiddleware

func CreateLatencyAndErrorMiddleware(params *Params) func(http.Handler) http.Handler

func CreateReplayReadMiddleware

func CreateReplayReadMiddleware(params *Params) func(http.Handler) http.Handler

CreateReplayReadMiddleware returns middleware that checks for a matching replay recording. Activates when the X-Cxs-Replay header is present, or when auto-replay is enabled in config for the matching endpoint. On hit, it returns the stored response with X-Cxs-Source: replay. On miss, it passes through to the next handler.

func CreateReplayWriteMiddleware

func CreateReplayWriteMiddleware(params *Params) func(http.Handler) http.Handler

CreateReplayWriteMiddleware returns middleware that records responses for replay. Activates when the X-Cxs-Replay header is present, or when auto-replay is enabled in config for the matching endpoint. It wraps downstream handlers, captures the response, and stores it indexed by match field values. Responses sourced from cache or replay are never recorded. When upstream-only is set, only upstream responses are recorded.

func CreateResourceResolverMiddleware

func CreateResourceResolverMiddleware(params *Params) func(http.Handler) http.Handler

CreateResourceResolverMiddleware resolves the OpenAPI spec resource path (e.g. /pets/{id}) from the request and stores it in the context.

func CreateUpstreamRequestMiddleware

func CreateUpstreamRequestMiddleware(params *Params) func(http.Handler) http.Handler

CreateUpstreamRequestMiddleware returns a middleware that fetches data from an upstream service.

func GetDuration

func GetDuration(r *http.Request) time.Duration

GetDuration returns the elapsed time since the request started.

func GetRequestID

func GetRequestID(r *http.Request) string

GetRequestID extracts the request ID set by chi's RequestID middleware.

func GetResourcePath

func GetResourcePath(req *http.Request) string

GetResourcePath returns the resolved OpenAPI resource path from the context. Falls back to the raw URL path if the context value is not set.

func GetUpstreamError

func GetUpstreamError(req *http.Request) string

GetUpstreamError returns the upstream error string stored in the request context, if any.

func LoggerMiddleware

func LoggerMiddleware(next http.Handler) http.Handler

LoggerMiddleware is a custom logging middleware

func RequestLog

func RequestLog(log *slog.Logger, r *http.Request) *slog.Logger

RequestLog returns a logger enriched with the request ID.

func SetDurationHeader

func SetDurationHeader(w http.ResponseWriter, r *http.Request)

SetDurationHeader sets X-Cxs-Duration header based on start time from context.

func SetRequestIDHeader

func SetRequestIDHeader(w http.ResponseWriter, r *http.Request)

SetRequestIDHeader sets the X-Cxs-Request-Id response header from context.

func StartTimeMiddleware

func StartTimeMiddleware(next http.Handler) http.Handler

StartTimeMiddleware stores request start time in context.

Types

type HistoryTransformFunc added in v2.1.71

type HistoryTransformFunc func(req *db.HistoryRequest, resp *db.HistoryResponse)

HistoryTransformFunc is a callback invoked before saving a history entry. It receives the request and response about to be stored and may modify them in place (e.g. masking sensitive headers or redacting body fields).

type Params

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

Params provides access to service configuration and database for middleware.

func NewParams

func NewParams(serviceConfig *config.ServiceConfig, database db.DB) *Params

NewParams creates a new Params instance with the given configuration and database.

func (*Params) DB

func (p *Params) DB() db.DB

DB returns the per-service database instance.

func (*Params) GetServiceConfig added in v2.1.68

func (p *Params) GetServiceConfig(req *http.Request) *config.ServiceConfig

GetServiceConfig returns the per-request service config from the context if set by the config override middleware, otherwise falls back to the shared config.

func (*Params) Logger

func (p *Params) Logger(middlewareName string) *slog.Logger

Logger returns a logger with the given middleware name added to the service context.

func (*Params) SetHistoryTransform added in v2.1.71

func (p *Params) SetHistoryTransform(fn HistoryTransformFunc)

SetHistoryTransform registers a callback that is invoked before each history entry is saved. The callback may modify the request and response in place. It runs before the mask-headers config is applied. Must be called during setup, before the server starts serving requests.

func (*Params) SetRouter

func (p *Params) SetRouter(r chi.Routes)

SetRouter stores the router for resource path resolution at request time.

type ReplayRecord

type ReplayRecord struct {
	Method         string            `json:"method"`
	Path           string            `json:"path"`
	Resource       string            `json:"resource,omitempty"`
	Data           []byte            `json:"data"`
	Headers        map[string]string `json:"headers"`
	StatusCode     int               `json:"statusCode"`
	ContentType    string            `json:"contentType"`
	IsFromUpstream bool              `json:"isFromUpstream"`
	RequestBody    []byte            `json:"requestBody"`
	MatchValues    map[string]any    `json:"matchValues"`
	CreatedAt      time.Time         `json:"createdAt"`
	HitCount       int               `json:"hitCount"`
	LastReplayedAt time.Time         `json:"lastReplayedAt,omitempty"`
}

ReplayRecord holds a recorded response along with request metadata for debugging.

Method is the HTTP method of the recorded request (e.g. GET, POST). Path is the actual request path (e.g. /pay/credit-card). Resource is the matched config endpoint pattern (e.g. /pay/{paymentMethod}). Empty when no config endpoint matched (header-only mode). Data is the response body bytes. Headers are the response headers (excluding internal X-Cxs-* headers). StatusCode is the HTTP status code of the response. ContentType is the Content-Type header of the response. IsFromUpstream is true if the response came from an upstream service. RequestBody is the original request body (stored for debugging). MatchValues maps field paths to their extracted values (stored for debugging). CreatedAt is when the recording was created. HitCount is the number of times this recording has been replayed. LastReplayedAt is the last time this recording was served.

Jump to

Keyboard shortcuts

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