Documentation
¶
Overview ¶
Package middleware provides HTTP server middlewares for keel services.
Every middleware is a github.com/foomo/keel/net/http.Middleware and is typically passed to an HTTP service or combined with github.com/foomo/keel/net/http.Compose:
svs := service.NewHTTP(l, "api", ":8080", handler, middleware.Telemetry(), middleware.Logger(), middleware.Recover(), )
Options ¶
Configurable middlewares follow the same pattern: Xxx(opts ...XxxOption) applies functional options to the defaults returned by GetDefaultXxxOptions and delegates to XxxWithOptions, which takes a fully populated XxxOptions.
Middlewares ¶
- Authentication: BasicAuth, TokenAuth, JWT and RBAC, with the token sources HeaderTokenProvider and CookieTokenProvider.
- Request context: RequestID, SessionID, TrackingID and Referer.
- Observability: Telemetry, Logger and ResponseTime.
- Transport: CORS, GZip, MaxRequestBodySize and ResponseController.
- Response headers: ServerHeader and PoweredByHeader.
- Safety: Recover.
Skip bypasses a middleware for requests matched by a Skipper, such as RequestURIBlacklistSkipper or RequestURIWhitelistSkipper.
Index ¶
- Constants
- Variables
- func BasicAuth(username string, passwordHash []byte, opts ...BasicAuthOption) keelhttp.Middleware
- func BasicAuthWithOptions(username string, passwordHash []byte, opts BasicAuthOptions) keelhttp.Middleware
- func CORS(opts ...CORSOption) keelhttp.Middleware
- func CORSWithOptions(opts CORSOptions) keelhttp.Middleware
- func DefaultJWTClaimsHandler(l *zap.Logger, w http.ResponseWriter, r *http.Request, claims gojwt.Claims) bool
- func DefaultJWTClaimsProvider() gojwt.Claims
- func DefaultJWTErrorHandler(l *zap.Logger, w http.ResponseWriter, r *http.Request, err error) bool
- func DefaultJWTInvalidTokenHandler(l *zap.Logger, w http.ResponseWriter, r *http.Request, token *gojwt.Token) bool
- func DefaultJWTMissingTokenHandler(l *zap.Logger, w http.ResponseWriter, r *http.Request) (gojwt.Claims, bool)
- func DefaultSessionIDGenerator() string
- func DefaultTrackingIDGenerator() string
- func GZip(opts ...GZipOption) keelhttp.Middleware
- func GZipWithOptions(opts GZipOptions) keelhttp.Middleware
- func JWT(v *jwt.JWT, contextKey any, opts ...JWTOption) keelhttp.Middleware
- func JWTWithOptions(v *jwt.JWT, contextKey any, opts JWTOptions) keelhttp.Middleware
- func Logger(opts ...LoggerOption) keelhttp.Middleware
- func LoggerWithOptions(opts LoggerOptions) keelhttp.Middleware
- func MaxRequestBodySize(n int64) keelhttp.Middleware
- func PoweredByHeader(opts ...PoweredByHeaderOption) keelhttp.Middleware
- func PoweredByHeaderWithOptions(opts PoweredByHeaderOptions) keelhttp.Middleware
- func RBAC(m *rbac.Matcher, extract rbac.RolesExtractor) keelhttp.Middleware
- func Recover(opts ...RecoverOption) keelhttp.Middleware
- func RecoverWithOptions(opts RecoverOptions) keelhttp.Middleware
- func Referer(opts ...RefererOption) keelhttp.Middleware
- func RefererWithOptions(opts RefererOptions) keelhttp.Middleware
- func RequestID(opts ...RequestIDOption) keelhttp.Middleware
- func RequestIDWithOptions(opts RequestIDOptions) keelhttp.Middleware
- func RequiredJWTMissingTokenHandler(l *zap.Logger, w http.ResponseWriter, r *http.Request) (gojwt.Claims, bool)
- func ResponseController(h func(rc *http.ResponseController) error) keelhttp.Middleware
- func ResponseTime(opts ...ResponseTimeOption) keelhttp.Middleware
- func ResponseTimeWithOptions(opts ResponseTimeOptions) keelhttp.Middleware
- func ServerHeader(opts ...ServerHeaderOption) keelhttp.Middleware
- func ServerHeaderWithOptions(opts ServerHeaderOptions) keelhttp.Middleware
- func SessionID(opts ...SessionIDOption) keelhttp.Middleware
- func SessionIDFromContext(ctx context.Context) string
- func SessionIDWithOptions(opts SessionIDOptions) keelhttp.Middleware
- func Skip(mw keelhttp.Middleware, skippers ...Skipper) keelhttp.Middleware
- func Telemetry(opts ...TelemetryOption) keelhttp.Middleware
- func TelemetryWithOptions(opts TelemetryOptions) keelhttp.Middleware
- func TokenAuth(token string, opts ...TokenAuthOption) keelhttp.Middleware
- func TokenAuthWithOptions(token string, opts TokenAuthOptions) keelhttp.Middleware
- func TrackingID(opts ...TrackingIDOption) keelhttp.Middleware
- func TrackingIDFromContext(ctx context.Context) string
- func TrackingIDWithOptions(opts TrackingIDOptions) keelhttp.Middleware
- func WrapResponseWriter(w http.ResponseWriter) *responseWriter
- type BasicAuthOption
- type BasicAuthOptions
- type CORSOption
- type CORSOptions
- type CookieTokenProviderOption
- type CookieTokenProviderOptions
- type GZipOption
- type GZipOptions
- type HeaderTokenProviderOption
- type HeaderTokenProviderOptions
- type JWTClaimsHandler
- type JWTClaimsProvider
- type JWTErrorHandler
- type JWTInvalidTokenHandler
- type JWTMissingTokenHandler
- type JWTOption
- func JWTWithClaimsHandler(v JWTClaimsHandler) JWTOption
- func JWTWithClaimsProvider(v JWTClaimsProvider) JWTOption
- func JWTWithErrorHandler(v JWTErrorHandler) JWTOption
- func JWTWithInvalidTokenHandler(v JWTInvalidTokenHandler) JWTOption
- func JWTWithMissingTokenHandler(v JWTMissingTokenHandler) JWTOption
- func JWTWithSetContext(v bool) JWTOption
- func JWTWithTokenProvider(v TokenProvider) JWTOption
- type JWTOptions
- type LoggerOption
- type LoggerOptions
- type PoweredByHeaderOption
- type PoweredByHeaderOptions
- type RecoverOption
- type RecoverOptions
- type RefererOption
- type RefererOptions
- type RequestIDOption
- func RequestIDWithGenerator(v provider.RequestID) RequestIDOption
- func RequestIDWithRequestHeader(v ...string) RequestIDOption
- func RequestIDWithResponseHeader(v string) RequestIDOption
- func RequestIDWithSetContext(v bool) RequestIDOption
- func RequestIDWithSetRequestHeader(v bool) RequestIDOption
- func RequestIDWithSetResponseHeader(v bool) RequestIDOption
- type RequestIDOptions
- type ResponseTimeOption
- type ResponseTimeOptions
- type ServerHeaderOption
- type ServerHeaderOptions
- type SessionIDGenerator
- type SessionIDOption
- func SessionIDWithCookie(v cookie.Cookie) SessionIDOption
- func SessionIDWithGenerator(v SessionIDGenerator) SessionIDOption
- func SessionIDWithHeader(v string) SessionIDOption
- func SessionIDWithSetContext(v bool) SessionIDOption
- func SessionIDWithSetCookie(v bool) SessionIDOption
- func SessionIDWithSetHeader(v bool) SessionIDOption
- type SessionIDOptions
- type Skipper
- type TelemetryOption
- type TelemetryOptions
- type TokenAuthOption
- type TokenAuthOptions
- type TokenProvider
- type TrackingIDGenerator
- type TrackingIDOption
- func TrackingIDWithCookie(v cookie.Cookie) TrackingIDOption
- func TrackingIDWithGenerator(v TrackingIDGenerator) TrackingIDOption
- func TrackingIDWithHeader(v string) TrackingIDOption
- func TrackingIDWithSetContext(v bool) TrackingIDOption
- func TrackingIDWithSetCookie(v bool) TrackingIDOption
- func TrackingIDWithSetHeader(v bool) TrackingIDOption
- type TrackingIDOptions
Examples ¶
Constants ¶
const (
// DefaultSessionIDCookieName is the default name of the session ID cookie.
DefaultSessionIDCookieName = "keel-session"
)
const (
// DefaultTrackingIDCookieName is the default name of the tracking ID cookie.
DefaultTrackingIDCookieName = "keel-tracking"
)
Variables ¶
var DefaultGZipOptions = GZipOptions{ CompressionLevel: gzip.DefaultCompression, MinSize: 1024, }
DefaultGZipOptions holds the defaults used by GZip: the default compression level, a minimum size of 1024 bytes and no decompression limit.
Functions ¶
func BasicAuth ¶
func BasicAuth(username string, passwordHash []byte, opts ...BasicAuthOption) keelhttp.Middleware
BasicAuth returns a middleware that requires HTTP basic authentication. The username is compared in constant time and the password is verified against passwordHash, which must be a bcrypt hash. Missing or invalid credentials are answered with 401 Unauthorized and a WWW-Authenticate challenge.
func BasicAuthWithOptions ¶ added in v0.2.0
func BasicAuthWithOptions(username string, passwordHash []byte, opts BasicAuthOptions) keelhttp.Middleware
BasicAuthWithOptions is like BasicAuth but takes fully populated options.
func CORS ¶
func CORS(opts ...CORSOption) keelhttp.Middleware
CORS returns a middleware that handles cross-origin resource sharing. Preflight (OPTIONS) requests are answered with 204 No Content and never reach the next handler, regardless of whether the origin is allowed. Other requests are always passed on and receive the CORS response headers only when their origin is allowed.
func CORSWithOptions ¶ added in v0.2.0
func CORSWithOptions(opts CORSOptions) keelhttp.Middleware
CORSWithOptions is like CORS but takes fully populated options.
func DefaultJWTClaimsHandler ¶ added in v0.12.0
func DefaultJWTClaimsHandler(l *zap.Logger, w http.ResponseWriter, r *http.Request, claims gojwt.Claims) bool
DefaultJWTClaimsHandler accepts all claims.
func DefaultJWTClaimsProvider ¶ added in v0.2.0
DefaultJWTClaimsProvider returns an empty gojwt.RegisteredClaims.
func DefaultJWTErrorHandler ¶ added in v0.2.0
DefaultJWTErrorHandler responds with 500 Internal Server Error and stops the request.
func DefaultJWTInvalidTokenHandler ¶ added in v0.2.0
func DefaultJWTInvalidTokenHandler(l *zap.Logger, w http.ResponseWriter, r *http.Request, token *gojwt.Token) bool
DefaultJWTInvalidTokenHandler responds with 400 Bad Request and stops the request.
func DefaultJWTMissingTokenHandler ¶ added in v0.2.0
func DefaultJWTMissingTokenHandler(l *zap.Logger, w http.ResponseWriter, r *http.Request) (gojwt.Claims, bool)
DefaultJWTMissingTokenHandler lets the request continue without claims.
func DefaultSessionIDGenerator ¶ added in v0.2.0
func DefaultSessionIDGenerator() string
DefaultSessionIDGenerator returns a random UUID string.
func DefaultTrackingIDGenerator ¶ added in v0.9.1
func DefaultTrackingIDGenerator() string
DefaultTrackingIDGenerator returns a random UUID string.
func GZip ¶ added in v0.19.0
func GZip(opts ...GZipOption) keelhttp.Middleware
GZip returns a middleware that compresses responses for clients accepting gzip and decompresses request bodies sent with Content-Encoding: gzip. The Content-Encoding and Content-Length request headers are removed for decompressed bodies. Malformed gzip bodies are answered with 400 Bad Request.
func GZipWithOptions ¶ added in v0.19.0
func GZipWithOptions(opts GZipOptions) keelhttp.Middleware
GZipWithOptions is like GZip but takes fully populated options. The returned middleware panics when applied if the options are invalid.
func JWT ¶ added in v0.2.0
JWT returns a middleware that parses and validates the request's JWT with v and stores the claims in the request context under contextKey. Requests whose context already holds a value for contextKey are passed on unchanged. A failing TokenProvider is answered with 400 Bad Request; all other outcomes are delegated to the handlers in JWTOptions.
func JWTWithOptions ¶ added in v0.2.0
func JWTWithOptions(v *jwt.JWT, contextKey any, opts JWTOptions) keelhttp.Middleware
JWTWithOptions is like JWT but takes fully populated options.
func Logger ¶
func Logger(opts ...LoggerOption) keelhttp.Middleware
Logger returns a middleware that logs one entry per request once the handler returns. The entry carries request fields, duration, status code, response size and any labeler fields; its level depends on the status code.
Example ¶
package main
import (
"fmt"
"net/http"
"github.com/foomo/keel/keeltest"
"github.com/foomo/keel/log"
"github.com/foomo/keel/net/http/middleware"
)
func main() {
svr := keeltest.NewExampleServer()
defer svr.Close()
// get logger
l := svr.Logger()
// create demo service
svs := http.NewServeMux()
svs.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
fmt.Println("ok")
})
svr.AddService(
keeltest.NewServiceHTTP(l, "demo", svs,
middleware.Logger(),
),
)
svr.Start()
resp, err := http.Get(svr.GetService("demo").URL() + "/") //nolint:noctx
log.Must(l, err)
defer resp.Body.Close()
}
Output: ok
func LoggerWithOptions ¶ added in v0.2.0
func LoggerWithOptions(opts LoggerOptions) keelhttp.Middleware
LoggerWithOptions is like Logger but takes fully populated options.
func MaxRequestBodySize ¶ added in v0.31.0
func MaxRequestBodySize(n int64) keelhttp.Middleware
MaxRequestBodySize middleware caps the request body at n bytes.
A declared Content-Length over the limit is rejected before the handler runs; otherwise the body is wrapped with http.MaxBytesReader, so a chunked or lying client fails on read with *http.MaxBytesError once it exceeds n. Handlers that read the body should surface that as 413:
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) { ... }
This bounds size; it does not bound time. A slow client trickling bytes under the limit is the server's ReadTimeout's problem — see ResponseController to adjust that per request.
func PoweredByHeader ¶ added in v0.2.6
func PoweredByHeader(opts ...PoweredByHeaderOption) keelhttp.Middleware
PoweredByHeader returns a middleware that adds a header, X-Powered-By by default, with the service name to every response.
func PoweredByHeaderWithOptions ¶ added in v0.2.6
func PoweredByHeaderWithOptions(opts PoweredByHeaderOptions) keelhttp.Middleware
PoweredByHeaderWithOptions is like PoweredByHeader but takes fully populated options.
func RBAC ¶ added in v0.26.0
func RBAC(m *rbac.Matcher, extract rbac.RolesExtractor) keelhttp.Middleware
RBAC middleware: a generic, path-based HTTP RBAC gate.
The middleware is transport-agnostic: only r.URL.Path and the caller-supplied roles drive the decision. It has no knowledge of any specific identity model — callers provide both the roles extractor and the configuration.
Typical wiring:
cfg, err := rbac.LoadConfigFromFile("/etc/rbac.yaml")
keellog.Must(l, err, "load rbac config")
matcher, err := rbac.NewMatcher(cfg)
keellog.Must(l, err, "compile rbac config")
mw := middleware.RBAC(matcher, extractRoles)
m and extract must be non-nil; they encode the decision contract and the middleware does not validate them per request.
Rule semantics: a request passes iff it hits no DenyRoles entry AND either the rule has no AllowRoles entries or roles intersect the AllowRoles set. Path matching picks the most specific rule (exact wins over longest matching prefix).
Denied requests log a structured zap warning ("rbac denied request") at WarnLevel with path, outcome, authenticated flag, roles, and matched rule path; allowed requests are not logged. The 401/403 split follows the extractor's authenticated flag: unauthenticated → 401, authenticated-but-disallowed → 403.
func Recover ¶
func Recover(opts ...RecoverOption) keelhttp.Middleware
Recover returns a middleware that recovers panics from the next handler, logs them and responds with 500 Internal Server Error. Panics with http.ErrAbortHandler are re-raised.
func RecoverWithOptions ¶ added in v0.2.0
func RecoverWithOptions(opts RecoverOptions) keelhttp.Middleware
RecoverWithOptions is like Recover but takes fully populated options.
func Referer ¶ added in v0.14.2
func Referer(opts ...RefererOption) keelhttp.Middleware
Referer returns a middleware that reads the referer from the first non-empty configured request header, records it on the span and stores it in the request context.
func RefererWithOptions ¶ added in v0.14.2
func RefererWithOptions(opts RefererOptions) keelhttp.Middleware
RefererWithOptions is like Referer but takes fully populated options.
func RequestID ¶
func RequestID(opts ...RequestIDOption) keelhttp.Middleware
RequestID returns a middleware that ensures every request has an ID, taken from the first non-empty configured request header or generated by the provider, and propagates it to the request, response and context.
func RequestIDWithOptions ¶ added in v0.2.0
func RequestIDWithOptions(opts RequestIDOptions) keelhttp.Middleware
RequestIDWithOptions is like RequestID but takes fully populated options.
func RequiredJWTMissingTokenHandler ¶ added in v0.2.0
func RequiredJWTMissingTokenHandler(l *zap.Logger, w http.ResponseWriter, r *http.Request) (gojwt.Claims, bool)
RequiredJWTMissingTokenHandler responds with 400 Bad Request and stops the request. Use it to make a token mandatory.
func ResponseController ¶ added in v0.31.0
func ResponseController(h func(rc *http.ResponseController) error) keelhttp.Middleware
ResponseController middleware runs h against the request's http.ResponseController before the handler, to override per connection what the server was constructed with: SetReadDeadline / SetWriteDeadline (the zero time clears a deadline), EnableFullDuplex, Flush.
// SSE: no write deadline
middleware.ResponseController(func(rc *http.ResponseController) error {
return rc.SetWriteDeadline(time.Time{})
})
// large upload: read for as long as it takes, bound the body instead
middleware.ResponseController(func(rc *http.ResponseController) error {
return rc.SetReadDeadline(time.Now().Add(10 * time.Minute))
})
An error from h is logged and the handler still runs — a ResponseWriter that does not support the operation must not fail the request.
IdleTimeout is out of reach here: it governs the connection between requests, when no handler is running, so there is nothing to hang a middleware on. It stays a server value (see keelhttp.NewServer) and must exceed the idle timeout of whatever sits in front of the pod — GCLB 600s, nginx-ingress 75s, ALB 60s — so that side always closes first. If the server expires first, the balancer hands the next request to a socket the server is closing and returns a 502.
func ResponseTime ¶ added in v0.2.0
func ResponseTime(opts ...ResponseTimeOption) keelhttp.Middleware
ResponseTime returns a middleware that measures the handler duration, sets the X-Response-Time header and logs a warning when the duration exceeds the configured maximum.
func ResponseTimeWithOptions ¶ added in v0.2.0
func ResponseTimeWithOptions(opts ResponseTimeOptions) keelhttp.Middleware
ResponseTimeWithOptions is like ResponseTime but takes fully populated options.
func ServerHeader ¶ added in v0.2.6
func ServerHeader(opts ...ServerHeaderOption) keelhttp.Middleware
ServerHeader returns a middleware that adds a header, Server by default, with the service name or the configured name to every response.
func ServerHeaderWithOptions ¶ added in v0.2.6
func ServerHeaderWithOptions(opts ServerHeaderOptions) keelhttp.Middleware
ServerHeaderWithOptions is like ServerHeader but takes fully populated options.
func SessionID ¶ added in v0.2.0
func SessionID(opts ...SessionIDOption) keelhttp.Middleware
SessionID returns a middleware that resolves the session ID from the request header or, failing that, the cookie. With SetCookie, a missing cookie is generated and set on both response and request. Cookie errors are answered with 500 Internal Server Error.
func SessionIDFromContext ¶ added in v0.2.0
SessionIDFromContext returns the session ID stored in ctx, or "" if there is none.
func SessionIDWithOptions ¶ added in v0.2.0
func SessionIDWithOptions(opts SessionIDOptions) keelhttp.Middleware
SessionIDWithOptions is like SessionID but takes fully populated options.
func Skip ¶ added in v0.2.0
func Skip(mw keelhttp.Middleware, skippers ...Skipper) keelhttp.Middleware
Skip returns a middleware that applies mw unless one of skippers reports true for the request, in which case next is called directly.
func Telemetry ¶
func Telemetry(opts ...TelemetryOption) keelhttp.Middleware
Telemetry returns a middleware that instruments the handler with otelhttp.NewHandler. It optionally injects the trace context into the response headers and, for sampled spans, adds the trace and span IDs to the request's log labeler.
func TelemetryWithOptions ¶ added in v0.2.0
func TelemetryWithOptions(opts TelemetryOptions) keelhttp.Middleware
TelemetryWithOptions is like Telemetry but takes fully populated options.
func TokenAuth ¶ added in v0.2.0
func TokenAuth(token string, opts ...TokenAuthOption) keelhttp.Middleware
TokenAuth returns a middleware that requires the request token to equal token, compared in constant time. Missing or mismatching tokens and provider errors are answered with 401 Unauthorized.
func TokenAuthWithOptions ¶ added in v0.2.0
func TokenAuthWithOptions(token string, opts TokenAuthOptions) keelhttp.Middleware
TokenAuthWithOptions is like TokenAuth but takes fully populated options.
func TrackingID ¶ added in v0.9.1
func TrackingID(opts ...TrackingIDOption) keelhttp.Middleware
TrackingID returns a middleware that resolves the tracking ID from the request header or, failing that, the cookie. With SetCookie, a missing cookie is generated and set on both response and request. Cookie errors are answered with 500 Internal Server Error.
func TrackingIDFromContext ¶ added in v0.9.1
TrackingIDFromContext returns the tracking ID stored in ctx, or "" if there is none.
func TrackingIDWithOptions ¶ added in v0.9.1
func TrackingIDWithOptions(opts TrackingIDOptions) keelhttp.Middleware
TrackingIDWithOptions is like TrackingID but takes fully populated options.
func WrapResponseWriter ¶ added in v0.2.0
func WrapResponseWriter(w http.ResponseWriter) *responseWriter
WrapResponseWriter wraps w to record the status code and body size. If w is already wrapped it is returned as is.
Types ¶
type BasicAuthOption ¶ added in v0.2.0
type BasicAuthOption func(*BasicAuthOptions)
BasicAuthOption configures BasicAuthOptions.
func BasicAuthWithRealm ¶ added in v0.2.0
func BasicAuthWithRealm(v string) BasicAuthOption
BasicAuthWithRealm sets the realm sent in the WWW-Authenticate challenge. Defaults to "Restricted".
type BasicAuthOptions ¶ added in v0.2.0
type BasicAuthOptions struct {
// Realm is the realm sent in the WWW-Authenticate challenge.
Realm string
}
BasicAuthOptions configures the BasicAuth middleware.
func GetDefaultBasicAuthOptions ¶ added in v0.2.0
func GetDefaultBasicAuthOptions() BasicAuthOptions
GetDefaultBasicAuthOptions returns the default options with the realm "Restricted".
type CORSOption ¶ added in v0.2.0
type CORSOption func(*CORSOptions)
CORSOption configures CORSOptions.
func CORSWithAllowCredentials ¶ added in v0.2.0
func CORSWithAllowCredentials(v bool) CORSOption
CORSWithAllowCredentials sets CORSOptions.AllowCredentials.
func CORSWithAllowHeaders ¶ added in v0.2.0
func CORSWithAllowHeaders(v ...string) CORSOption
CORSWithAllowHeaders sets CORSOptions.AllowHeaders.
func CORSWithAllowMethods ¶ added in v0.2.0
func CORSWithAllowMethods(v ...string) CORSOption
CORSWithAllowMethods sets CORSOptions.AllowMethods.
func CORSWithAllowOrigins ¶ added in v0.2.0
func CORSWithAllowOrigins(v ...string) CORSOption
CORSWithAllowOrigins sets CORSOptions.AllowOrigins.
func CORSWithExposeHeaders ¶ added in v0.2.0
func CORSWithExposeHeaders(v ...string) CORSOption
CORSWithExposeHeaders sets CORSOptions.ExposeHeaders.
func CORSWithMaxAge ¶ added in v0.2.0
func CORSWithMaxAge(v int) CORSOption
CORSWithMaxAge sets CORSOptions.MaxAge.
type CORSOptions ¶ added in v0.2.0
type CORSOptions struct {
// AllowOrigins lists the allowed origins. "*" allows any origin. Entries
// may contain the wildcards "*" (any sequence) and "?" (any single
// character), e.g. "https://*.example.com".
AllowOrigins []string
// AllowMethods lists the methods sent in Access-Control-Allow-Methods
// on preflight responses.
AllowMethods []string
// AllowHeaders lists the headers sent in Access-Control-Allow-Headers on
// preflight responses. When empty, the request's
// Access-Control-Request-Headers value is echoed.
AllowHeaders []string
// AllowCredentials reports whether Access-Control-Allow-Credentials is
// sent. When set together with the "*" origin, the request origin is
// echoed instead of "*".
AllowCredentials bool
// ExposeHeaders lists the headers sent in Access-Control-Expose-Headers
// on non-preflight responses.
ExposeHeaders []string
// MaxAge is the Access-Control-Max-Age in seconds sent on preflight
// responses. Zero omits the header.
MaxAge int
}
CORSOptions configures the CORS middleware.
func GetDefaultCORSOptions ¶ added in v0.2.0
func GetDefaultCORSOptions() CORSOptions
GetDefaultCORSOptions returns the default options, which allow any origin and the methods GET, HEAD, PUT, PATCH, POST and DELETE.
type CookieTokenProviderOption ¶ added in v0.2.0
type CookieTokenProviderOption func(*CookieTokenProviderOptions)
CookieTokenProviderOption configures CookieTokenProviderOptions.
type CookieTokenProviderOptions ¶ added in v0.2.0
type CookieTokenProviderOptions struct{}
CookieTokenProviderOptions configures CookieTokenProvider. It has no fields and exists for API symmetry with the other token providers.
func GetDefaultCookieTokenOptions ¶ added in v0.2.0
func GetDefaultCookieTokenOptions() CookieTokenProviderOptions
GetDefaultCookieTokenOptions returns the default options.
type GZipOption ¶ added in v0.19.0
type GZipOption func(*GZipOptions)
GZipOption configures GZipOptions.
func GZipWithLevel ¶ added in v0.19.0
func GZipWithLevel(v int) GZipOption
GZipWithLevel allows setting a specific compression level for gzip (default: gzip.DefaultCompression).
func GZipWithMaxDecompressedSize ¶ added in v0.29.0
func GZipWithMaxDecompressedSize(v int64) GZipOption
GZipWithMaxDecompressedSize caps the decompressed request body size in bytes to guard against decompression bombs. Requests exceeding the limit are rejected with 413 (default: 0, unlimited).
func GZipWithMinSize ¶ added in v0.19.0
func GZipWithMinSize(v int) GZipOption
GZipWithMinSize allows setting a minimum response body length to apply gzip compression (default: 1024 bytes).
type GZipOptions ¶ added in v0.19.0
type GZipOptions struct {
// CompressionLevel is the gzip level used to compress responses.
CompressionLevel int
// MinSize is the minimum response body size in bytes to compress.
MinSize int
// MaxDecompressedSize caps the number of decompressed request body bytes
// accepted (guards against decompression bombs). Zero means unlimited.
MaxDecompressedSize int64
}
GZipOptions configures the GZip middleware.
type HeaderTokenProviderOption ¶ added in v0.2.0
type HeaderTokenProviderOption func(*HeaderTokenProviderOptions)
HeaderTokenProviderOption configures HeaderTokenProviderOptions.
func HeaderTokenProviderWithHeader ¶ added in v0.2.0
func HeaderTokenProviderWithHeader(v string) HeaderTokenProviderOption
HeaderTokenProviderWithHeader sets the request header holding the token. Defaults to Authorization.
func HeaderTokenProviderWithPrefix ¶ added in v0.2.0
func HeaderTokenProviderWithPrefix(v string) HeaderTokenProviderOption
HeaderTokenProviderWithPrefix sets the required value prefix. Defaults to "Bearer ".
type HeaderTokenProviderOptions ¶ added in v0.2.0
type HeaderTokenProviderOptions struct {
// Prefix is the required value prefix, stripped from the token.
Prefix string
// Header is the name of the request header holding the token.
Header string
}
HeaderTokenProviderOptions configures HeaderTokenProvider.
func GetDefaultHeaderTokenOptions ¶ added in v0.2.0
func GetDefaultHeaderTokenOptions() HeaderTokenProviderOptions
GetDefaultHeaderTokenOptions returns the default options, which read a bearer token from the Authorization header.
type JWTClaimsHandler ¶ added in v0.12.0
JWTClaimsHandler is called with the claims of a valid token and reports whether the request continues, with the claims in its context.
type JWTClaimsProvider ¶ added in v0.2.0
JWTClaimsProvider returns a new, empty claims value to parse a token into. It is called once per request.
type JWTErrorHandler ¶ added in v0.2.0
JWTErrorHandler is called when parsing a token fails and reports whether the request continues without claims.
type JWTInvalidTokenHandler ¶ added in v0.2.0
type JWTInvalidTokenHandler func(*zap.Logger, http.ResponseWriter, *http.Request, *gojwt.Token) bool
JWTInvalidTokenHandler is called when a token parses but is not valid and reports whether the request continues without claims.
type JWTMissingTokenHandler ¶ added in v0.2.0
type JWTMissingTokenHandler func(*zap.Logger, http.ResponseWriter, *http.Request) (gojwt.Claims, bool)
JWTMissingTokenHandler is called when the request carries no token. It returns optional claims to store in the context and reports whether the request continues.
type JWTOption ¶ added in v0.2.0
type JWTOption func(*JWTOptions)
JWTOption configures JWTOptions.
func JWTWithClaimsHandler ¶ added in v0.12.0
func JWTWithClaimsHandler(v JWTClaimsHandler) JWTOption
JWTWithClaimsHandler sets JWTOptions.ClaimsHandler.
func JWTWithClaimsProvider ¶ added in v0.2.0
func JWTWithClaimsProvider(v JWTClaimsProvider) JWTOption
JWTWithClaimsProvider sets JWTOptions.ClaimsProvider.
func JWTWithErrorHandler ¶ added in v0.2.0
func JWTWithErrorHandler(v JWTErrorHandler) JWTOption
JWTWithErrorHandler sets JWTOptions.ErrorHandler.
func JWTWithInvalidTokenHandler ¶ added in v0.2.0
func JWTWithInvalidTokenHandler(v JWTInvalidTokenHandler) JWTOption
JWTWithInvalidTokenHandler sets JWTOptions.InvalidTokenHandler.
func JWTWithMissingTokenHandler ¶ added in v0.2.0
func JWTWithMissingTokenHandler(v JWTMissingTokenHandler) JWTOption
JWTWithMissingTokenHandler sets JWTOptions.MissingTokenHandler.
func JWTWithSetContext ¶ added in v0.2.1
JWTWithSetContext sets JWTOptions.SetContext. Defaults to true.
func JWTWithTokenProvider ¶ added in v0.2.0
func JWTWithTokenProvider(v TokenProvider) JWTOption
JWTWithTokenProvider sets JWTOptions.TokenProvider.
type JWTOptions ¶ added in v0.2.0
type JWTOptions struct {
// SetContext reports whether a present token is parsed, validated and
// its claims stored in the request context. When false, a present
// token is neither parsed nor validated and the request is passed on
// unchanged.
SetContext bool
// TokenProvider extracts the token from the request.
TokenProvider TokenProvider
// ClaimsProvider returns the claims value a token is parsed into.
ClaimsProvider JWTClaimsProvider
// ClaimsHandler is called with the claims of a valid token.
ClaimsHandler JWTClaimsHandler
// MissingTokenHandler is called when the request carries no token.
MissingTokenHandler JWTMissingTokenHandler
// InvalidTokenHandler is called when a token parses but is not valid.
InvalidTokenHandler JWTInvalidTokenHandler
// ErrorHandler is called when parsing or validating a token fails.
ErrorHandler JWTErrorHandler
}
JWTOptions configures the JWT middleware.
func GetDefaultJWTOptions ¶ added in v0.2.0
func GetDefaultJWTOptions() JWTOptions
GetDefaultJWTOptions returns the default options: SetContext enabled, a HeaderTokenProvider and the Default* handlers of this package.
type LoggerOption ¶ added in v0.2.0
type LoggerOption func(*LoggerOptions)
LoggerOption configures LoggerOptions.
func LoggerWithInjectLabeler ¶ added in v0.14.0
func LoggerWithInjectLabeler(v bool) LoggerOption
LoggerWithInjectLabeler sets LoggerOptions.InjectLabeler. Defaults to true.
Example ¶
package main
import (
"fmt"
"net/http"
"github.com/foomo/keel/keeltest"
"github.com/foomo/keel/log"
httplog "github.com/foomo/keel/net/http/log"
"github.com/foomo/keel/net/http/middleware"
"go.uber.org/zap"
)
func main() {
svr := keeltest.NewExampleServer()
defer svr.Close()
// get logger
l := svr.Logger()
// create demo service
svs := http.NewServeMux()
svs.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
fmt.Println("ok")
})
svr.AddService(
keeltest.NewServiceHTTP(l, "demo", svs,
func(l *zap.Logger, s string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if labeler, ok := httplog.LabelerFromRequest(r); ok {
labeler.Add(zap.String("injected", "message"))
}
next.ServeHTTP(w, r)
})
},
middleware.Logger(
middleware.LoggerWithInjectLabeler(true),
),
),
)
svr.Start()
resp, err := http.Get(svr.GetService("demo").URL() + "/") //nolint:noctx
log.Must(l, err)
defer resp.Body.Close()
}
Output: ok
func LoggerWithMessage ¶ added in v0.2.4
func LoggerWithMessage(v string) LoggerOption
LoggerWithMessage sets the log message.
func LoggerWithMinErrorCode ¶ added in v0.11.6
func LoggerWithMinErrorCode(v int) LoggerOption
LoggerWithMinErrorCode sets the status code from which requests are logged at error level. Defaults to 500.
func LoggerWithMinWarnCode ¶ added in v0.11.6
func LoggerWithMinWarnCode(v int) LoggerOption
LoggerWithMinWarnCode sets the status code from which requests are logged at warn level. Defaults to 400.
type LoggerOptions ¶ added in v0.2.0
type LoggerOptions struct {
// Message is the log message.
Message string
// MinWarnCode is the status code from which requests are logged at
// warn level. Zero disables it.
MinWarnCode int
// MinErrorCode is the status code from which requests are logged at
// error level. Zero disables it.
MinErrorCode int
// InjectLabeler reports whether a log labeler is injected into the
// request so downstream handlers can add fields to the log entry.
InjectLabeler bool
}
LoggerOptions configures the Logger middleware.
func GetDefaultLoggerOptions ¶ added in v0.2.0
func GetDefaultLoggerOptions() LoggerOptions
GetDefaultLoggerOptions returns the default options: message "handled http request", warn from 400, error from 500 and labeler injection enabled.
type PoweredByHeaderOption ¶ added in v0.2.6
type PoweredByHeaderOption func(*PoweredByHeaderOptions)
PoweredByHeaderOption configures PoweredByHeaderOptions.
func PoweredByHeaderWithHeader ¶ added in v0.2.6
func PoweredByHeaderWithHeader(v string) PoweredByHeaderOption
PoweredByHeaderWithHeader sets the response header name. Defaults to X-Powered-By.
func PoweredByHeaderWithMessage ¶ added in v0.2.6
func PoweredByHeaderWithMessage(v string) PoweredByHeaderOption
PoweredByHeaderWithMessage sets PoweredByHeaderOptions.Message.
type PoweredByHeaderOptions ¶ added in v0.2.6
type PoweredByHeaderOptions struct {
// Header is the name of the response header.
Header string
// Message is not used; the header value is the service name.
Message string
}
PoweredByHeaderOptions configures the PoweredByHeader middleware.
func GetDefaultPoweredByHeaderOptions ¶ added in v0.2.6
func GetDefaultPoweredByHeaderOptions() PoweredByHeaderOptions
GetDefaultPoweredByHeaderOptions returns the default options using the X-Powered-By header.
type RecoverOption ¶ added in v0.2.0
type RecoverOption func(*RecoverOptions)
RecoverOption configures RecoverOptions.
func RecoverWithDisablePrintStack ¶ added in v0.2.0
func RecoverWithDisablePrintStack(v bool) RecoverOption
RecoverWithDisablePrintStack sets RecoverOptions.DisablePrintStack.
type RecoverOptions ¶ added in v0.2.0
type RecoverOptions struct {
// DisablePrintStack reports whether the stack trace is omitted from
// the log entry.
DisablePrintStack bool
}
RecoverOptions configures the Recover middleware.
func GetDefaultRecoverOptions ¶ added in v0.2.0
func GetDefaultRecoverOptions() RecoverOptions
GetDefaultRecoverOptions returns the default options, which include the stack trace.
type RefererOption ¶ added in v0.14.2
type RefererOption func(*RefererOptions)
RefererOption configures RefererOptions.
func RefererWithRequestHeader ¶ added in v0.14.2
func RefererWithRequestHeader(v ...string) RefererOption
RefererWithRequestHeader appends headers to RefererOptions.RequestHeader.
func RefererWithSetContext ¶ added in v0.14.2
func RefererWithSetContext(v bool) RefererOption
RefererWithSetContext sets RefererOptions.SetContext. Defaults to true.
type RefererOptions ¶ added in v0.14.2
type RefererOptions struct {
// RequestHeader lists the request headers checked in order; the first
// non-empty value is used.
RequestHeader []string
// SetContext reports whether the referer is stored in the request
// context.
SetContext bool
}
RefererOptions configures the Referer middleware.
func GetDefaultRefererOptions ¶ added in v0.14.2
func GetDefaultRefererOptions() RefererOptions
GetDefaultRefererOptions returns the default options, which read the X-Referer and Referer headers and set the context.
type RequestIDOption ¶ added in v0.2.0
type RequestIDOption func(*RequestIDOptions)
RequestIDOption configures RequestIDOptions.
func RequestIDWithGenerator ¶ added in v0.2.0
func RequestIDWithGenerator(v provider.RequestID) RequestIDOption
RequestIDWithGenerator sets RequestIDOptions.Provider. Defaults to provider.DefaultRequestID.
func RequestIDWithRequestHeader ¶ added in v0.11.3
func RequestIDWithRequestHeader(v ...string) RequestIDOption
RequestIDWithRequestHeader appends headers to RequestIDOptions.RequestHeader.
func RequestIDWithResponseHeader ¶ added in v0.2.0
func RequestIDWithResponseHeader(v string) RequestIDOption
RequestIDWithResponseHeader sets RequestIDOptions.ResponseHeader. Defaults to X-Request-ID.
func RequestIDWithSetContext ¶ added in v0.11.3
func RequestIDWithSetContext(v bool) RequestIDOption
RequestIDWithSetContext sets RequestIDOptions.SetContext. Defaults to true.
func RequestIDWithSetRequestHeader ¶ added in v0.11.3
func RequestIDWithSetRequestHeader(v bool) RequestIDOption
RequestIDWithSetRequestHeader sets RequestIDOptions.SetRequestHeader. Defaults to true.
func RequestIDWithSetResponseHeader ¶ added in v0.2.0
func RequestIDWithSetResponseHeader(v bool) RequestIDOption
RequestIDWithSetResponseHeader sets RequestIDOptions.SetResponseHeader. Defaults to true.
type RequestIDOptions ¶ added in v0.2.0
type RequestIDOptions struct {
// Provider generates a request ID when the request carries none.
Provider provider.RequestID
// RequestHeader lists the request headers checked in order; the first
// non-empty value is used.
RequestHeader []string
// ResponseHeader is the name of the header the ID is written to.
ResponseHeader string
// SetRequestHeader reports whether the ID is set on the request,
// using the ResponseHeader name.
SetRequestHeader bool
// SetResponseHeader reports whether the ID is added to the response
// unless the header is already present.
SetResponseHeader bool
// SetContext reports whether the ID is stored in the request context.
SetContext bool
}
RequestIDOptions configures the RequestID middleware.
func GetDefaultRequestIDOptions ¶ added in v0.2.0
func GetDefaultRequestIDOptions() RequestIDOptions
GetDefaultRequestIDOptions returns the default options, which read the X-Request-ID and Cf-Ray headers, write X-Request-ID and enable all Set flags.
type ResponseTimeOption ¶ added in v0.2.0
type ResponseTimeOption func(*ResponseTimeOptions)
ResponseTimeOption configures ResponseTimeOptions.
func ResponseTimeWithMaxDuration ¶ added in v0.2.0
func ResponseTimeWithMaxDuration(v time.Duration) ResponseTimeOption
ResponseTimeWithMaxDuration sets the duration above which a warning is logged. Defaults to 0, which disables the warning.
func ResponseTimeWithMaxDurationMessage ¶ added in v0.2.0
func ResponseTimeWithMaxDurationMessage(v string) ResponseTimeOption
ResponseTimeWithMaxDurationMessage sets the warning message. Defaults to "max response time exceeded".
func ResponseTimeWithSetHeader ¶ added in v0.2.0
func ResponseTimeWithSetHeader(v bool) ResponseTimeOption
ResponseTimeWithSetHeader sets ResponseTimeOptions.SetHeader. Defaults to true.
type ResponseTimeOptions ¶ added in v0.2.0
type ResponseTimeOptions struct {
// SetHeader reports whether the X-Response-Time header, the time in
// microseconds until the response header is written, is set.
SetHeader bool
// MaxDuration is the duration above which a warning is logged. Zero
// disables the warning.
MaxDuration time.Duration
// MaxDurationMessage is the message of that warning.
MaxDurationMessage string
}
ResponseTimeOptions configures the ResponseTime middleware.
func GetDefaultResponseTimeOptions ¶ added in v0.2.0
func GetDefaultResponseTimeOptions() ResponseTimeOptions
GetDefaultResponseTimeOptions returns the default options, which set the header and log no warnings.
type ServerHeaderOption ¶ added in v0.2.6
type ServerHeaderOption func(*ServerHeaderOptions)
ServerHeaderOption configures ServerHeaderOptions.
func ServerHeaderWithHeader ¶ added in v0.2.6
func ServerHeaderWithHeader(v string) ServerHeaderOption
ServerHeaderWithHeader sets the response header name. Defaults to Server.
func ServerHeaderWithName ¶ added in v0.2.6
func ServerHeaderWithName(v string) ServerHeaderOption
ServerHeaderWithName sets the header value. Defaults to the service name.
type ServerHeaderOptions ¶ added in v0.2.6
type ServerHeaderOptions struct {
// Header is the name of the response header.
Header string
// Name is the header value. When empty, the service name is used.
Name string
}
ServerHeaderOptions configures the ServerHeader middleware.
func GetDefaultServerHeaderOptions ¶ added in v0.2.6
func GetDefaultServerHeaderOptions() ServerHeaderOptions
GetDefaultServerHeaderOptions returns the default options using the Server header and the service name.
type SessionIDGenerator ¶ added in v0.2.0
type SessionIDGenerator func() string
SessionIDGenerator returns a new session ID.
type SessionIDOption ¶ added in v0.2.0
type SessionIDOption func(*SessionIDOptions)
SessionIDOption configures SessionIDOptions.
func SessionIDWithCookie ¶ added in v0.2.0
func SessionIDWithCookie(v cookie.Cookie) SessionIDOption
SessionIDWithCookie sets SessionIDOptions.Cookie.
func SessionIDWithGenerator ¶ added in v0.2.0
func SessionIDWithGenerator(v SessionIDGenerator) SessionIDOption
SessionIDWithGenerator sets SessionIDOptions.Generator. Defaults to DefaultSessionIDGenerator.
func SessionIDWithHeader ¶ added in v0.2.0
func SessionIDWithHeader(v string) SessionIDOption
SessionIDWithHeader sets SessionIDOptions.Header. Defaults to X-Session-ID.
func SessionIDWithSetContext ¶ added in v0.2.0
func SessionIDWithSetContext(v bool) SessionIDOption
SessionIDWithSetContext sets SessionIDOptions.SetContext. Defaults to true.
func SessionIDWithSetCookie ¶ added in v0.2.0
func SessionIDWithSetCookie(v bool) SessionIDOption
SessionIDWithSetCookie sets SessionIDOptions.SetCookie. Defaults to false.
func SessionIDWithSetHeader ¶ added in v0.2.0
func SessionIDWithSetHeader(v bool) SessionIDOption
SessionIDWithSetHeader sets SessionIDOptions.SetHeader. Defaults to true.
type SessionIDOptions ¶ added in v0.2.0
type SessionIDOptions struct {
// Header is the request header the session ID is read from and, with
// SetHeader, written to.
Header string
// Cookie is the cookie the session ID is read from and, with SetCookie,
// written to.
Cookie cookie.Cookie
// Generator creates a session ID when SetCookie is enabled and the
// request carries none.
Generator SessionIDGenerator
// SetCookie reports whether a session ID is generated and set as cookie
// when the request carries neither header nor cookie.
SetCookie bool
// SetHeader reports whether the session ID is set as request header.
SetHeader bool
// SetContext reports whether the session ID is stored in the request
// context.
SetContext bool
}
SessionIDOptions configures the SessionID middleware.
func GetDefaultSessionIDOptions ¶ added in v0.2.0
func GetDefaultSessionIDOptions() SessionIDOptions
GetDefaultSessionIDOptions returns the default options: the X-Session-ID header, a cookie named "keel-session", UUID generation, SetHeader and SetContext enabled and SetCookie disabled.
type Skipper ¶ added in v0.2.0
Skipper reports whether a middleware should be skipped for the request.
func RequestURIBlacklistSkipper ¶ added in v0.2.0
RequestURIBlacklistSkipper returns a Skipper that skips requests whose RequestURI, including the query, exactly matches one of uris.
func RequestURIWhitelistSkipper ¶ added in v0.2.0
RequestURIWhitelistSkipper returns a Skipper that skips all requests except those whose RequestURI, including the query, exactly matches one of uris.
type TelemetryOption ¶ added in v0.2.0
type TelemetryOption func(*TelemetryOptions)
TelemetryOption configures TelemetryOptions.
func TelemetryWithInjectPropagationHeader ¶ added in v0.9.12
func TelemetryWithInjectPropagationHeader(v bool) TelemetryOption
TelemetryWithInjectPropagationHeader sets TelemetryOptions.InjectPropagationHeader. Defaults to true.
func TelemetryWithName ¶ added in v0.2.6
func TelemetryWithName(v string) TelemetryOption
TelemetryWithName sets TelemetryOptions.Name. Defaults to the service name.
func TelemetryWithOtelOpts ¶ added in v0.2.6
func TelemetryWithOtelOpts(v ...otelhttp.Option) TelemetryOption
TelemetryWithOtelOpts appends options passed to otelhttp.NewHandler.
type TelemetryOptions ¶ added in v0.2.0
type TelemetryOptions struct {
// Name is the operation name passed to otelhttp. When empty, the
// service name is used.
Name string
// OtelOpts are passed to [otelhttp.NewHandler].
OtelOpts []otelhttp.Option
// InjectPropagationHeader reports whether the trace context is
// injected into the response headers.
InjectPropagationHeader bool
}
TelemetryOptions configures the Telemetry middleware.
func GetDefaultTelemetryOptions ¶ added in v0.2.0
func GetDefaultTelemetryOptions() TelemetryOptions
GetDefaultTelemetryOptions returns the default options, which inject the propagation header.
type TokenAuthOption ¶ added in v0.2.0
type TokenAuthOption func(*TokenAuthOptions)
TokenAuthOption configures TokenAuthOptions.
func TokenAuthWithTokenProvider ¶ added in v0.2.0
func TokenAuthWithTokenProvider(v TokenProvider) TokenAuthOption
TokenAuthWithTokenProvider sets TokenAuthOptions.TokenProvider. Defaults to HeaderTokenProvider.
type TokenAuthOptions ¶ added in v0.2.0
type TokenAuthOptions struct {
// TokenProvider extracts the token from the request.
TokenProvider TokenProvider
}
TokenAuthOptions configures the TokenAuth middleware.
func GetDefaultTokenAuthOptions ¶ added in v0.2.0
func GetDefaultTokenAuthOptions() TokenAuthOptions
GetDefaultTokenAuthOptions returns the default options using a HeaderTokenProvider.
type TokenProvider ¶ added in v0.2.0
TokenProvider extracts an authentication token from the request. It returns an empty token and a nil error when the request carries none.
func CookieTokenProvider ¶ added in v0.2.0
func CookieTokenProvider(cookieName string, opts ...CookieTokenProviderOption) TokenProvider
CookieTokenProvider returns a TokenProvider that reads the token from the cookie named cookieName. A missing cookie yields an empty token and no error.
func HeaderTokenProvider ¶ added in v0.2.0
func HeaderTokenProvider(opts ...HeaderTokenProviderOption) TokenProvider
HeaderTokenProvider returns a TokenProvider that reads the token from a request header and strips the configured prefix. A missing header yields an empty token and no error; a value without the prefix yields an error.
type TrackingIDGenerator ¶ added in v0.9.1
type TrackingIDGenerator func() string
TrackingIDGenerator returns a new tracking ID.
type TrackingIDOption ¶ added in v0.9.1
type TrackingIDOption func(*TrackingIDOptions)
TrackingIDOption configures TrackingIDOptions.
func TrackingIDWithCookie ¶ added in v0.9.1
func TrackingIDWithCookie(v cookie.Cookie) TrackingIDOption
TrackingIDWithCookie sets TrackingIDOptions.Cookie.
func TrackingIDWithGenerator ¶ added in v0.9.1
func TrackingIDWithGenerator(v TrackingIDGenerator) TrackingIDOption
TrackingIDWithGenerator sets TrackingIDOptions.Generator. Defaults to DefaultTrackingIDGenerator.
func TrackingIDWithHeader ¶ added in v0.9.1
func TrackingIDWithHeader(v string) TrackingIDOption
TrackingIDWithHeader sets TrackingIDOptions.Header. Defaults to X-Tracking-ID.
func TrackingIDWithSetContext ¶ added in v0.9.1
func TrackingIDWithSetContext(v bool) TrackingIDOption
TrackingIDWithSetContext sets TrackingIDOptions.SetContext. Defaults to true.
func TrackingIDWithSetCookie ¶ added in v0.9.1
func TrackingIDWithSetCookie(v bool) TrackingIDOption
TrackingIDWithSetCookie sets TrackingIDOptions.SetCookie. Defaults to false.
func TrackingIDWithSetHeader ¶ added in v0.9.1
func TrackingIDWithSetHeader(v bool) TrackingIDOption
TrackingIDWithSetHeader sets TrackingIDOptions.SetHeader. Defaults to true.
type TrackingIDOptions ¶ added in v0.9.1
type TrackingIDOptions struct {
// Header is the request header the tracking ID is read from and, with
// SetHeader, written to.
Header string
// Cookie is the cookie the tracking ID is read from and, with SetCookie,
// written to.
Cookie cookie.Cookie
// Generator creates a tracking ID when SetCookie is enabled and the
// request carries none.
Generator TrackingIDGenerator
// SetCookie reports whether a tracking ID is generated and set as cookie
// when the request carries neither header nor cookie.
SetCookie bool
// SetHeader reports whether the tracking ID is set as request header.
SetHeader bool
// SetContext reports whether the tracking ID is stored in the request
// context.
SetContext bool
}
TrackingIDOptions configures the TrackingID middleware.
func GetDefaultTrackingIDOptions ¶ added in v0.9.1
func GetDefaultTrackingIDOptions() TrackingIDOptions
GetDefaultTrackingIDOptions returns the default options: the X-Tracking-ID header, a cookie named "keel-tracking", UUID generation, SetHeader and SetContext enabled and SetCookie disabled.
Source Files
¶
- basicauth.go
- cookietokenprovider.go
- cors.go
- doc.go
- gzip.go
- headertokenprovider.go
- jwt.go
- logger.go
- maxrequestbodysize.go
- poweredbyheader.go
- rbac.go
- recover.go
- referrer.go
- requestid.go
- requesturiblacklistskipper.go
- requesturiwhitelistskipper.go
- responsecontroller.go
- responsetime.go
- responsewriter.go
- serverheader.go
- sessionid.go
- skip.go
- skipper.go
- telemetry.go
- tokenauth.go
- tokenprovider.go
- trackingid.go