middleware

package
v0.0.0-...-d333732 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2026 License: BSD-3-Clause Imports: 18 Imported by: 0

Documentation

Overview

Package middleware provides middleware commonly-required for Web servers. All middleware follow the conventional signature of a function accepting an http.Handler and returning an http.Handler, making them compatible with a wide variety of third-party Go packages that compose middleware (such as the popular github.com/justinas/alice package).

Index

Constants

View Source
const ErrTooManyBytes = errors.ConstError("too many bytes written to the response")

ErrTooManyBytes is returned by the LimitResponseBodyBytes middleware if too many bytes get written to the response body.

Variables

This section is empty.

Functions

func AllowMethodOverride

func AllowMethodOverride() func(http.Handler) http.Handler

AllowMethodOverride returns a middleware that checks for the X-HTTP-Method-Override header or the _method form key, and overrides (if valid) Request.Method with its value. This middleware uses the github.com/gorilla/handlers package.

This is especially useful for HTTP clients that don't support many http verbs. It isn't secure to override e.g a GET to a POST, so only POST requests are considered. Likewise, the override method can only be a "write" method: PUT, PATCH or DELETE.

Form method takes precedence over header method.

Note that for the proper routing to be done, this middleware should run before the router's dispatch to the corresponding handler (that is, this middleware should wrap the route multiplexer).

func CORS

func CORS(config *CORSConfig) func(http.Handler) http.Handler

CORS returns a middleware that configures CORS requests according to the config options. It uses the third-party github.com/jub0bs/fcors package. It panics if the configuration is invalid, the fcors package is strict in what it accepts.

Because CORS-preflight requests use OPTIONS as their HTTP method, the resources to which you apply a CORS middleware should accept OPTIONS requests.

func CanonicalHost

func CanonicalHost(domain string, code int) func(http.Handler) http.Handler

CanonicalHost returns a middleware that redirects requests to the canonical domain. It accepts a domain and a status code (e.g. 301 or 302) and redirects clients to this domain. The existing request path is maintained.

Note: If the provided domain is considered invalid by url.Parse or otherwise returns an empty scheme or host, clients are not redirected.

This middleware uses the github.com/gorilla/handlers package.

func Compress

func Compress(config *CompressConfig) func(http.Handler) http.Handler

Compress returns a middleware that transparently provides response body compression. It uses the github.com/CAFxX/httpcompression third-party package.

func CustomErrors

func CustomErrors(
	errHandler func(code int, w http.ResponseWriter, r *http.Request) (handled bool),
) func(http.Handler) http.Handler

CustomErrors returns a middleware that wraps a handler (e.g. http.FileServer or any handler that writes errors in a simple, straightforward sequence of calls to w.WriteHeader followed by w.Write, such as calls to the http.Error function) and directs any error (status code >= 400) to the custom error handler, that can decide to handle it or fallback to the default handling.

The custom error function should ensure the response headers are properly set if it handles the error, no special handling of headers is done by the middleware.

func LimitRequestBodyBytes

func LimitRequestBodyBytes(limit int64) func(http.Handler) http.Handler

LimitRequestBodyBytes returns a middleware that limits the number of bytes that can be read from the request's body to limit. If more bytes are read, it fails the read with an error of type *http.MaxBytesError.

func LimitResponseBodyBytes

func LimitResponseBodyBytes(limit int64) func(http.Handler) http.Handler

LimitResponseBodyBytes returns a middleware that limits the number of bytes that can be written to the response. If the number of bytes written exceeds the limit, the write fails with ErrTooManyBytes and the HTTP response header is written with status code 500 (which may or may not be sent to the client, depending if the headers were already written).

func Logging

func Logging(reqIDHeader string, logFn func(http.ResponseWriter, *http.Request, map[string]any)) func(http.Handler) http.Handler

Logging returns a middleware that collects relevant information about the request and calls logFn with that information. If logFn is nil, it uses ctxvals.LoggerOr to retrieve the logger and logs the information with all key-value pairs. If the reqIDHeader is provided, the request ID is retrieved and added to the logging data. It uses the github.com/felixge/httpsnoop package to capture request metrics.

It calls ctxvals.WithLogKeyValue so the request's context can be used with ctxvals.SetLogKeyValue to add key-value pairs to log with the request.

func PanicRecovery

func PanicRecovery(recoverFn func(http.ResponseWriter, *http.Request, any, []byte)) func(http.Handler) http.Handler

PanicRecovery returns a middleware that recovers from a panic, calling recoverFn with the response writer, the request, the panic value and the call stack to handle the response to the failed request.

func RequestContentType

func RequestContentType(contentTypes []string) func(http.Handler) http.Handler

RequestContentType returns a middleware that validates that the request's content-type is one of the supported types of the server. It fails the request with status code 415 Unsupported Media Type if that's not the case. This uses the github.com/gorilla/handlers third-party package.

The content type is the MIME type format, e.g. "application/json".

func RequestID

func RequestID(header string, force bool) func(http.Handler) http.Handler

RequestID returns a middleware that generates a unique request ID and sets it on the specified request's and response's header. If force is true it generates a new request ID even if the request header already has a value.

func RequestLimit

func RequestLimit(config *RequestLimitConfig) func(http.Handler) http.Handler

RequestLimit returns a middleware that limits the number of requests to the handler using a token bucket and returns a status code 503 Service Unavailable when the number of requests exceed the capacity. It uses the github.com/juju/ratelimit package for rate-limiting.

func RequestTimeouts

func RequestTimeouts(readTimeout, writeTimeout time.Duration) func(http.Handler) http.Handler

RequestTimeouts returns a middleware that sets request-specific read and write timeouts that override any server-wide timeouts, by calling SetReadDeadline and SetWriteDeadline of the http.ResponseController. A zero timeout means no timeout, and a negative timeout keeps the server setting.

func ResponseContentType

func ResponseContentType(offeredTypes []string) func(http.Handler) http.Handler

ResponseContentType returns a middleware that validates the Accept header passed by the request against the offered types by the server. If no supported content type is available, it fails the request with status code 406 Not Acceptable. Otherwise it sets the response's Content-Type header to the negotiated type.

func StripPrefix

func StripPrefix(prefix string) func(http.Handler) http.Handler

StripPrefix returns a middleware that serves HTTP requests by removing the given prefix from the request URL's Path (and RawPath if set) and invoking the handler h.

It uses the standard library's http.StripPrefix.

func TimeoutHandler

func TimeoutHandler(timeout time.Duration) func(http.Handler) http.Handler

TimeoutHandler returns a middleware that uses http.TimeoutHandler to fail the request with status code 503 Service Unavailable if it takes too long to run. After such a timeout, writes by the handler to its ResponseWriter will return http.ErrHandlerTimeout.

func TrustProxyHeaders

func TrustProxyHeaders() func(http.Handler) http.Handler

TrustProxyHeaders returns a middleware that inspects common reverse proxy headers and sets the corresponding fields in the HTTP request struct. These are X-Forwarded-For and X-Real-IP for the remote (client) IP address, X-Forwarded-Proto or X-Forwarded-Scheme for the scheme (http|https), X-Forwarded-Host for the host and the RFC7239 Forwarded header, which may include both client IPs and schemes.

Make sure that you use this middleware if you actually trust/control the proxy in front of your Go web server. This middleware uses the github.com/gorilla/handlers package.

Types

type CORSConfig

type CORSConfig struct {
	// AllowCredentials allows both anonymous access and credentialed access
	// (e.g. with cookies) when set to true, according to the specified options.
	// Otherwise, only anonymous access is allowed.
	AllowCredentials bool
	// AllowedOrigins is the list of origins allowed to make CORS requests. If a
	// single origin equal to "*" is set, any origin is accepted. See the
	// third-party package's documentation for more details.
	AllowedOrigins []string
	// AllowedMethods is the list of HTTP methods allowed to make CORS requests.
	// If a single method equal to "*" is set, any method is accepted.
	AllowedMethods []string
	// AllowedRequestHeaders is the list of headers accepted as part of the CORS
	// request. Header names are case-insensitive. If a single header equal to
	// "*" is set, any request header is allowed.
	AllowedRequestHeaders []string
	// ExposedResponseHeaders is the list of headers allowed to be exposed to the
	// client side of a CORS request. If a single header equal to "*" is set, all
	// response headers are exposed.
	ExposedResponseHeaders []string
	// MaxAge is the maximum duration to cache preflight responses by clients
	// (browsers). A negative value instructs browsers to eschew caching of
	// preflight responses altogether, while the default value of 0 causes
	// browsers to cache preflight responses with a default max-age value of 5
	// seconds. Note that the value is translated to a number of seconds, smaller
	// fractions are truncated.
	MaxAge time.Duration
}

CORSConfig provides configuration options for the CORS middleware.

type CompressConfig

type CompressConfig struct {
	// ContentTypes lists the response MIME content types to consider using
	// compression. Typically, text content types are more compressable, while
	// many binary content types are already optimized for size.
	ContentTypes []string

	// MinSize specifies the minimum size of the response body to consider using
	// compression. A value <= 0 uses the middleware's default.
	MinSize int
}

CompressConfig provides configuration options for the compression middleware of response bodies.

type RequestLimitConfig

type RequestLimitConfig struct {
	// Rate fills the bucket at the rate of rate tokens per second up to the
	// given maximum capacity. Leave FillInterval <= 0 to use a rate-based
	// bucket.
	Rate float64
	// FillInterval filles the bucket at the rate of Quantum token every
	// FillInterval, up to the given maximum capacity.
	FillInterval time.Duration
	// Capacity is the maximum number of tokens in the bucket.
	Capacity int64
	// Quantum indicates the number of tokens to add at FillInterval. If 0, a
	// value of 1 is used.
	Quantum int64
	// MaxWait is the maximum time to wait for tokens to become available. If 0,
	// the middleware will not allow the request through as soon as the required
	// token is not immediately available.
	MaxWait time.Duration
}

RequestLimitConfig is the configuration for the RequestLimit middleware.

Jump to

Keyboard shortcuts

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