middleware

package
v9.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 30 Imported by: 0 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.

Documentation

Overview

Package middleware contains helpers for adding standard behavior like authentication and metrics to REST endpoints.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AcquireInitSlot

func AcquireInitSlot(limiter *concurrency.Limiter, recorder InitShedRecorder, w http.ResponseWriter, r *http.Request) (release func(), ok bool)

AcquireInitSlot draws one slot from the shared initialization-delivery limiter for the current request, holding it until the returned release is called. If the budget is full it writes a 503 (with a JSON body) and returns ok=false; the caller must then write nothing further. A disabled or nil limiter always admits with a no-op release, so callers can invoke this unconditionally.

The response write itself is bounded separately, by the progress-aware writer that LimitConcurrency / ProvideInitLimiter install, so a slow client cannot park the slot.

It is called both by LimitConcurrency (which gates a whole handler, e.g. the PHP all-flags poll) and directly by the FDv2 poll handlers and the FDv1 /sdk/latest-all handler. Those acquire only for a full payload, so a cheap up-to-date or 304 reply is never charged.

func AcquireInitSlotFromContext

func AcquireInitSlotFromContext(w http.ResponseWriter, r *http.Request) (release func(), ok bool)

AcquireInitSlotFromContext acquires a slot from the limiter installed by ProvideInitLimiter, with the same semantics as AcquireInitSlot. If no limiter was provided (or it is disabled) it admits with a no-op release, so a handler can call it unconditionally on its full-basis path.

func CORS

func CORS(next http.Handler) http.Handler

CORS is a middleware function that sets the appropriate CORS headers on a browser response (not counting Access-Control-Allow-Methods, which is set by gorilla/mux's CORS middleware based on the route handlers we've defined).

Also, if the HTTP method is OPTIONS, it will short-circuit the rest of the middleware chain so that the underlying handler is *not* called-- since an OPTIONS request should not do anything except set the CORS response headers. Therefore, we should always put the gorilla/mux CORS middleware before this one.

func Chain

func Chain(middlewares ...mux.MiddlewareFunc) mux.MiddlewareFunc

Chain combines a series of middleware functions that will be applied in the same order.

func ContextFromBase64

func ContextFromBase64(base64Context string) (ldcontext.Context, error)

ContextFromBase64 decodes a base64-encoded go-server-sdk evaluation context. If any decoding/unmarshaling errors occur, or the decoded context is invalid by the rules of the Go SDK, an error is returned.

func CountBrowserConns

func CountBrowserConns(handler http.Handler) http.Handler

CountBrowserConns is a middleware function that increments the number of active browser connections until the handler ends.

func CountClientConns

func CountClientConns(handler http.Handler) http.Handler

CountClientConns is a middleware function for FDv2 client-side endpoints that dynamically determines whether to count as mobile or browser connections based on the credential type.

func CountMobileConns

func CountMobileConns(handler http.Handler) http.Handler

CountMobileConns is a middleware function that increments the number of active mobile connections until the handler ends.

func CountServerConns

func CountServerConns(handler http.Handler) http.Handler

CountServerConns is a middleware function that increments the number of active server-side connections until the handler ends.

func DynamicPollingRequestCount

func DynamicPollingRequestCount(handler http.Handler) http.Handler

DynamicPollingRequestCount is a middleware function for FDv2 client-side endpoints that dynamically determines the polling request metric based on the credential type.

func DynamicTrackUsageActivity

func DynamicTrackUsageActivity() mux.MiddlewareFunc

DynamicTrackUsageActivity is like TrackUsageActivity but determines the platform category at request time based on the credential type, for FDv2 unified client-side endpoints.

func DynamicUsageActivityStreamMonitoring

func DynamicUsageActivityStreamMonitoring(next http.Handler) http.Handler

DynamicUsageActivityStreamMonitoring is like UsageActivityStreamMonitoring but determines the platform category at request time based on the credential type, for FDv2 unified client-side endpoints.

func EventBytesMetrics

func EventBytesMetrics() mux.MiddlewareFunc

EventBytesMetrics is a middleware function that records the number of event bytes received. This should be applied after GzipMiddleware so that it measures decompressed bytes.

func GzipMiddleware

func GzipMiddleware(maxInboundPayloadSize ct.OptBase2Bytes) mux.MiddlewareFunc

func LimitConcurrency

func LimitConcurrency(limiter *concurrency.Limiter, maxHold time.Duration, recorder InitShedRecorder) func(http.Handler) http.Handler

LimitConcurrency wraps a handler with the shared initialization-delivery limiter for a request whose whole response is a full-dataset delivery (the PHP all-flags poll). The slot is acquired on entry and held until the handler returns, and the response is written through a progress-aware writer (see initwrite) so a slow or stalled client cannot park the slot. On shed it responds 503 and does not invoke the wrapped handler. A disabled or nil limiter is a pass-through with zero overhead. Handlers that have a cheap no-payload branch (the FDv2 polls and the FDv1 /sdk/latest-all poll) should instead call AcquireInitSlot directly, after that branch, so the cheap reply is not charged.

func ProvideInitLimiter

func ProvideInitLimiter(limiter *concurrency.Limiter, maxHold time.Duration, recorder InitShedRecorder) func(http.Handler) http.Handler

ProvideInitLimiter makes the shared initialization-delivery limiter available to a downstream handler via the request context, without acquiring a slot, and wraps the response in the progress-aware writer. It is used for the FDv2 poll endpoints and the FDv1 /sdk/latest-all poll. Their handlers acquire lazily (via AcquireInitSlotFromContext) only for a full payload, so a cheap up-to-date or 304 reply is never charged. A disabled or nil limiter is a pass-through with zero overhead.

func RequestMetrics

func RequestMetrics(endpointType metrics.EndpointType) mux.MiddlewareFunc

RequestMetrics is a middleware function that tracks a request in http.server.active_requests for as long as it is in flight, and records its duration once it completes.

Active requests cover every request this middleware sees, streaming included, per the OTEL semantic convention for the instrument. Duration is still skipped for streaming responses, whose lifetime is unbounded.

There is no platform-dependent variant of this: since these metrics dropped platform.category, the SDK platform no longer changes what gets recorded.

func SanitizeRequestSpan

func SanitizeRequestSpan(next http.Handler) http.Handler

SanitizeRequestSpan corrects two problems with the attributes the HTTP tracing middleware records on the request span. Attributes cannot be removed from a span once set, but they are deduplicated last-write-wins when they are read, so overwriting a value here is what keeps the original out of the exported trace.

First, url.path holds the raw request path, which on routes that take an evaluation context contains the end user's data: keys, names, emails and custom attributes. Only that one segment is replaced, with the REDACTED placeholder the semantic conventions use for scrubbing a URL, so the rest of the path -- which identifies the endpoint and the environment, and is not sensitive -- survives. Routes with no context variable keep their real path.

Second, three of the recorded attributes come from request data that is not restricted to valid UTF-8, and OTLP cannot serialize a span carrying an invalid byte -- the marshal fails and the whole export batch is dropped. They are:

user_agent.original  the User-Agent header
client.address       the X-Forwarded-For header, used unvalidated
url.path             the percent-decoded request path

This list is specific to the instrumentation in use and will need revisiting if it starts recording further attributes from request data; TestSpanAttributesAreValidUTF8 fails if that happens.

This must be registered after the middleware that starts the request span.

func SelectEnvironmentByAuthorizationKey

func SelectEnvironmentByAuthorizationKey(sdkKind basictypes.SDKKind, envs RelayEnvironments) mux.MiddlewareFunc

SelectEnvironmentByAuthorizationKey creates a middleware function that attempts to authenticate the request using the appropriate kind of credential for the basictypes.SDKKind. If successful, it updates the request context so GetEnvContextInfo will return environment information. If not successful, it returns an error response.

func SelectEnvironmentByClientSideAuth

func SelectEnvironmentByClientSideAuth(envs RelayEnvironments) mux.MiddlewareFunc

SelectEnvironmentByClientSideAuth creates a middleware function that authenticates the request using either a mobile key or environment ID. The credential type is determined by inspecting the token value: tokens starting with "mob-" are treated as mobile keys, otherwise as environment IDs. The token is extracted from the Authorization header or the "auth" query parameter.

func ServerPollingRequestCount

func ServerPollingRequestCount(handler http.Handler) http.Handler

ServerPollingRequestCount is a middleware function that increments the total number of server-side polling requests.

func Streaming

func Streaming(next http.Handler) http.Handler

Streaming is a middleware function that sets the appropriate headers on a streaming response.

func TrackUsageActivity

func TrackUsageActivity(platformCategory string) mux.MiddlewareFunc

func UnscopedActiveRequests

func UnscopedActiveRequests(manager *metrics.Manager, endpointType metrics.EndpointType) mux.MiddlewareFunc

UnscopedActiveRequests tracks a request in http.server.active_requests without an LD environment, for endpoints that have no environment to attribute the request to. Its launchdarkly.environment.name attribute is the not_provided sentinel.

This is applied directly to a handler rather than registered with Router.Use for requests that matched no route: gorilla/mux skips router middleware entirely when a request fails to match.

func UsageActivityStreamMonitoring

func UsageActivityStreamMonitoring(platformCategory string, next http.Handler) http.Handler

func WithEnvContextInfo

func WithEnvContextInfo(ctx context.Context, info EnvContextInfo) context.Context

WithEnvContextInfo returns a new Context with the EnvContextInfo added.

Types

type EnvContextInfo

type EnvContextInfo struct {
	// Env is an existing EnvContext object for the environment.
	Env relayenv.EnvContext

	// Credential is the SDK key, mobile key, or environment ID that was used in the request.
	Credential credential.SDKCredential
}

EnvContextInfo is data that we attach to the current HTTP request to indicate which environment it is related to.

func GetEnvContextInfo

func GetEnvContextInfo(ctx context.Context) EnvContextInfo

GetEnvContextInfo returns the EnvContextInfo that is attached to the specified Context (normally obtained from a request as request.Context()). It panics if there is none, since this context data is supposed to be injected by our middleware and our handlers cannot work without it.

type InitShedRecorder

type InitShedRecorder interface {
	RecordPollShed(envName string)
}

InitShedRecorder counts polling requests the initialization-delivery budget shed. The metrics package implements it. A nil recorder is permitted and records nothing.

type RelayEnvironments

type RelayEnvironments interface {
	// GetEnvironment returns the environment corresponding to scopedCred, or an error if no matching
	// environment could be found.
	GetEnvironment(scopedCred credential.SDKCredential) (env relayenv.EnvContext, err error)
	// IsNotReady should return true if the error returned by GetEnvironment represents the fact that Relay is not yet
	// fully configured.
	IsNotReady(error) bool
}

RelayEnvironments defines the methods for looking up environments. This is represented as an interface so that test code can mock that capability.

Jump to

Keyboard shortcuts

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