middleware

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MetricApiRequestsActive     = "%s_api_requests_active"
	MetricApiRequestsTotal      = "%s_api_requests_total"
	MetricApiRequestErrorsTotal = "%s_api_request_errors_total"
	MetricApiRequestLatencyMs   = "%s_api_request_latency_ms"
)

Variables

This section is empty.

Functions

func ApiMinifier

func ApiMinifier(httproutes map[string]bool) func(http.Handler) http.Handler

ApiMinifier is a middleware that sets a specific header to the response if the request URL path is in the provided map and the corresponding value is true.

Parameters:

  • httproutes: A map where the keys are URL paths and the values indicate whether the response for that path should be minified.

Returns:

A middleware function that can be used with an HTTP handler.

func CleanPath

func CleanPath(next http.Handler) http.Handler

func Compress

func Compress(level int, types ...string) func(next http.Handler) http.Handler

Compress is a middleware that compresses response body of a given content types to a data format based on Accept-Encoding request header. It uses a given compression level.

NOTE: make sure to set the Content-Type header on your response otherwise this middleware will not compress the response body. For ex, in your handler you should set w.Header().Set("Content-Type", http.DetectContentType(yourBody)) or set it manually.

Passing a compression level of 5 is sensible value

func GetHead

func GetHead(next http.Handler) http.Handler

func GetLocale

func GetLocale(ctx context.Context) string

Get locale value from request context

func GetRequestID

func GetRequestID(ctx context.Context) string

Retrieve unique request id from the provided context object.

func Heartbeat

func Heartbeat(endpoint string) func(http.Handler) http.Handler

Heartbeat endpoint middleware useful to setting up a path like `/ping` that load balancers or uptime testing external services can make a request before hitting any routes. It's also convenient to place this above ACL middlewares as well.

func OTelMeterMiddleware

func OTelMeterMiddleware(service string) func(http.Handler) http.Handler

OTelMeterMiddleware tracks total requests, errors, latency, and active request count.

func OTelTracerMiddleware

func OTelTracerMiddleware(operationName string, tracer trace.Tracer) func(http.Handler) http.Handler

OTelTracerMiddleware is a middleware that wraps an HTTP handler with OpenTelemetry tracing. It creates a span for the incoming request and sets various attributes on the span. The span is ended after the request is processed, and the latency is recorded.

func RateLimitMiddleware

func RateLimitMiddleware(limiter ratelimiter.Limiter, log logger.Logger, timeout time.Duration) func(http.Handler) http.Handler

RateLimitMiddleware returns an HTTP middleware that applies rate limiting using the provided limiter and logger. It extracts the rate limit key from the request (e.g., IP address or header).

func RealIP

func RealIP(h http.Handler) http.Handler

RealIP is a middleware that sets a http.Request's RemoteAddr to the results of parsing either the True-Client-IP, X-Real-IP or the X-Forwarded-For headers (in that order).

This middleware should be inserted fairly early in the middleware stack to ensure that subsequent layers (e.g., request loggers) which examine the RemoteAddr will see the intended value.

You should only use this middleware if you can trust the headers passed to you (in particular, the two headers this middleware uses), for example because you have placed a reverse proxy like HAProxy or nginx in front of router. If your reverse proxies are configured to pass along arbitrary header values from the client, or if you use this middleware without a reverse proxy, malicious clients will be able to make you very sad (or, depending on how you're using RemoteAddr, vulnerable to an attack of some sort).

func Recoverer

func Recoverer(logger logger.Logger) func(http.Handler) http.Handler

Recoverer middleware catches the panic that have occurred during program execution, and recovers from them. It logs the panic details and stack trace into log files, and also sends an error http response to the client if it is in middle of a web request.

func RequestId

func RequestId(next http.Handler) http.Handler

RequestId middleware creates a unique and random request id for each http request, and thats that into request context, so the same can be used by the application as an unique identifier. This same request id is also added to the http response header so the similar correlation can be created at client side as well.

func RequestInit

func RequestInit(next http.Handler) http.Handler

Application request initialiser middleware. All the init actions should be done here that are to be performed before the request execution starts.

ParseForm reads r.Body for form-encoded POSTs which would leave downstream handlers with an empty body. Buffer the body first, reset it after ParseForm, so handlers that need the raw payload (e.g. webhook signature verification) can still read it.

func RequestLogger

func RequestLogger(logger logger.Logger) func(http.Handler) http.Handler

RequestLogger middleware logs all the request specific parameters along with the profiling informatilon to the provided logger (file/stream).

func SecurityHeaders

func SecurityHeaders(next http.Handler) http.Handler

Add security http headers to the response object, to avoid the common security loopholes and threats. In future more sophisticated security hooks can also be added here.

func SecurityHeadersWithOptions added in v1.0.1

func SecurityHeadersWithOptions(options SecurityHeadersOptions) func(http.Handler) http.Handler

func SetLocale

func SetLocale(r *http.Request, locale string) *http.Request

Set locale value to the request context

func Timeout

func Timeout(duration time.Duration) func(http.Handler) http.Handler

Timeout creates a middleware that sets a timeout for HTTP requests.

Types

type Compressor

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

Compressor represents a set of encoding configurations.

func NewCompressor

func NewCompressor(level int, types ...string) *Compressor

NewCompressor creates a new Compressor that will handle encoding responses.

The level should be one of the ones defined in the flate package. The types are the content types that are allowed to be compressed.

func (*Compressor) Handler

func (c *Compressor) Handler(next http.Handler) http.Handler

Handler returns a new middleware that will compress the response based on the current Compressor.

func (*Compressor) SetEncoder

func (c *Compressor) SetEncoder(encoding string, fn EncoderFunc)

SetEncoder can be used to set the implementation of a compression algorithm.

The encoding should be a standardised identifier. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding

For example, add the Brotli algorithm:

import brotli_enc "gopkg.in/kothar/brotli-go.v0/enc"

compressor := middleware.NewCompressor(5, "text/html")
compressor.SetEncoder("br", func(w io.Writer, level int) io.Writer {
  params := brotli_enc.NewBrotliParams()
  params.SetQuality(level)
  return brotli_enc.NewBrotliWriter(params, w)
})

type ContextLocaleKey

type ContextLocaleKey string

Context key type for locale

const LocaleKey ContextLocaleKey = "locale"

type EncoderFunc

type EncoderFunc func(w io.Writer, level int) io.Writer

An EncoderFunc is a function that wraps the provided io.Writer with a streaming compression algorithm and returns it.

In case of failure, the function should return nil.

type MiddlewareFn

type MiddlewareFn func(http.HandlerFunc) http.HandlerFunc

Conscious call to build over net/http package to support public middleware packages built over and above net/http package

func ToMiddlewareFn

func ToMiddlewareFn(mw func(http.Handler) http.Handler) MiddlewareFn

Convert `func(http.Handler) http.Handler` to MiddlewareFn

type SecurityHeadersOptions added in v1.0.1

type SecurityHeadersOptions struct {
	XFrameOptions           string
	XContentTypeOptions     string
	ReferrerPolicy          string
	PermissionsPolicy       string
	CrossOriginOpenerPolicy string
	XSSProtection           string
	ContentSecurityPolicy   string
}

type WrapResponseWriter

type WrapResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

WrapResponseWriter wraps http.ResponseWriter to capture status code and bytes written.

func NewWrapResponseWriter

func NewWrapResponseWriter(w http.ResponseWriter) *WrapResponseWriter

NewWrapResponseWriter creates a new WrapResponseWriter.

func (*WrapResponseWriter) BytesWritten

func (ww *WrapResponseWriter) BytesWritten() int

BytesWritten returns the number of bytes written.

func (*WrapResponseWriter) Flush

func (ww *WrapResponseWriter) Flush()

Flush preserves http.Flusher for handlers that stream responses.

func (*WrapResponseWriter) Hijack

func (ww *WrapResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack preserves http.Hijacker for websocket and raw TCP upgrades.

func (*WrapResponseWriter) Push

func (ww *WrapResponseWriter) Push(target string, opts *http.PushOptions) error

Push preserves http.Pusher when HTTP/2 server push is available.

func (*WrapResponseWriter) ReadFrom

func (ww *WrapResponseWriter) ReadFrom(r io.Reader) (int64, error)

ReadFrom preserves io.ReaderFrom fast paths while keeping byte counts correct.

func (*WrapResponseWriter) Status

func (ww *WrapResponseWriter) Status() int

Status returns the captured status code.

func (*WrapResponseWriter) Write

func (ww *WrapResponseWriter) Write(b []byte) (int, error)

Write wraps the Write method to capture the number of bytes written.

func (*WrapResponseWriter) WriteHeader

func (ww *WrapResponseWriter) WriteHeader(code int)

WriteHeader wraps the WriteHeader method to capture the status code.

Jump to

Keyboard shortcuts

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