middleware

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2025 License: MIT Imports: 20 Imported by: 6

Documentation

Overview

Package middleware contains set of middlewares for HTTP server.

Example
package main

import (
	"net/http"
	"time"

	"github.com/go-chi/chi/v5"

	"github.com/acronis/go-appkit/log"
)

func main() {
	const errDomain = "MyService"

	logger, closeFn := log.NewLogger(&log.Config{Output: log.OutputStdout, Format: log.FormatJSON})
	defer closeFn()

	router := chi.NewRouter()

	router.Use(
		RequestID(),
		LoggingWithOpts(logger, LoggingOpts{RequestStart: true}),
		Recovery(errDomain),
		RequestBodyLimit(1024*1024, errDomain),
	)

	metricsCollector := NewHTTPRequestPrometheusMetrics()
	router.Use(HTTPRequestMetricsWithOpts(metricsCollector, getChiRoutePattern, HTTPRequestMetricsOpts{
		ExcludedEndpoints: []string{"/metrics", "/healthz"}, // Metrics will not be collected for "/metrics" and "/healthz" endpoints.
	}))

	userCreateInFlightLimitMiddleware := MustInFlightLimitWithOpts(32, errDomain, InFlightLimitOpts{
		GetKey: func(r *http.Request) (string, bool, error) {
			key := r.Header.Get("X-Client-ID")
			return key, key == "", nil
		},
		MaxKeys:            1000,
		ResponseStatusCode: http.StatusTooManyRequests,
		GetRetryAfter: func(r *http.Request) time.Duration {
			return time.Second * 15
		},
		BacklogLimit:   64,
		BacklogTimeout: time.Second * 10,
	})

	usersListRateLimitMiddleware := MustRateLimit(Rate{Count: 100, Duration: time.Second}, errDomain)

	router.Route("/users", func(r chi.Router) {
		r.With(usersListRateLimitMiddleware).Get("/", func(rw http.ResponseWriter, req *http.Request) {
			// Returns list of users.
		})
		r.With(userCreateInFlightLimitMiddleware).Post("/", func(rw http.ResponseWriter, req *http.Request) {
			// Create new user.
		})
	})
}

// Example of how this function may look for gorilla/mux router is given in the RoutePatternGetterFunc documentation.
// GetChiRoutePattern extracts chi route pattern from request.
func getChiRoutePattern(r *http.Request) string {
	// modified code from https://github.com/go-chi/chi/issues/270#issuecomment-479184559
	rctx := chi.RouteContext(r.Context())
	if rctx == nil {
		return ""
	}
	if pattern := rctx.RoutePattern(); pattern != "" {
		// Pattern is already available
		return pattern
	}

	routePath := r.URL.RawPath
	if routePath == "" {
		routePath = r.URL.Path
	}

	tctx := chi.NewRouteContext()
	if !rctx.Routes.Match(tctx, r.Method, routePath) {
		return ""
	}
	return tctx.RoutePattern()
}
Output:

Index

Examples

Constants

View Source
const (
	InFlightLimitLogFieldKey        = "in_flight_limit_key"
	InFlightLimitLogFieldBacklogged = "in_flight_limit_backlogged"
)

Log fields for InFlightLimit middleware.

View Source
const DefaultInFlightLimitBacklogTimeout = time.Second * 5

DefaultInFlightLimitBacklogTimeout determines how long the HTTP request may be in the backlog status.

View Source
const DefaultInFlightLimitMaxKeys = 10000

DefaultInFlightLimitMaxKeys is a default value of maximum keys number for the InFlightLimit middleware.

View Source
const DefaultRateLimitBacklogTimeout = time.Second * 5

DefaultRateLimitBacklogTimeout determines how long the HTTP request may be in the backlog status.

View Source
const DefaultRateLimitMaxKeys = 10000

DefaultRateLimitMaxKeys is a default value of maximum keys number for the RateLimit middleware.

View Source
const InFlightLimitErrCode = "tooManyInFlightRequests"

InFlightLimitErrCode is the error code that is used in a response body if the request is rejected by the middleware that limits in-flight HTTP requests.

View Source
const (
	// LoggingSecretQueryPlaceholder represents a placeholder that will be used for secret query parameters.
	LoggingSecretQueryPlaceholder = "_HIDDEN_"
)
View Source
const RateLimitErrCode = "tooManyRequests"

RateLimitErrCode is an error code that is used in a response body if the request is rejected by the middleware that limits the rate of HTTP requests.

View Source
const RateLimitLogFieldKey = "rate_limit_key"

RateLimitLogFieldKey it is the name of the logged field that contains a key for the requests rate limiter.

View Source
const RecoveryDefaultStackSize = 8192

RecoveryDefaultStackSize defines the default size of stack part which will be logged.

Variables

View Source
var DefaultHTTPRequestDurationBuckets = []float64{0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 150, 300, 600}

DefaultHTTPRequestDurationBuckets is default buckets into which observations of serving HTTP requests are counted.

Functions

func DefaultInFlightLimitOnError

func DefaultInFlightLimitOnError(
	rw http.ResponseWriter, r *http.Request, params InFlightLimitParams, err error, next http.Handler, logger log.FieldLogger,
)

DefaultInFlightLimitOnError sends HTTP response in a typical go-appkit way in case when the error occurs during the in-flight limiting.

func DefaultInFlightLimitOnReject

func DefaultInFlightLimitOnReject(
	rw http.ResponseWriter, r *http.Request, params InFlightLimitParams, next http.Handler, logger log.FieldLogger,
)

DefaultInFlightLimitOnReject sends HTTP response in a typical go-appkit way when the in-flight limit is exceeded.

func DefaultInFlightLimitOnRejectInDryRun

func DefaultInFlightLimitOnRejectInDryRun(
	rw http.ResponseWriter, r *http.Request, params InFlightLimitParams, next http.Handler, logger log.FieldLogger,
)

DefaultInFlightLimitOnRejectInDryRun sends HTTP response in a typical go-appkit way when the in-flight limit is exceeded in the dry-run mode.

func DefaultRateLimitOnError

func DefaultRateLimitOnError(
	rw http.ResponseWriter, r *http.Request, params RateLimitParams, err error, next http.Handler, logger log.FieldLogger,
)

DefaultRateLimitOnError sends HTTP response in a typical go-appkit way in case when the error occurs during the in-flight limiting.

func DefaultRateLimitOnReject

func DefaultRateLimitOnReject(
	rw http.ResponseWriter, r *http.Request, params RateLimitParams, next http.Handler, logger log.FieldLogger,
)

DefaultRateLimitOnReject sends HTTP response in a typical go-appkit way when the rate limit is exceeded.

func DefaultRateLimitOnRejectInDryRun

func DefaultRateLimitOnRejectInDryRun(
	rw http.ResponseWriter, r *http.Request, params RateLimitParams, next http.Handler, logger log.FieldLogger,
)

DefaultRateLimitOnRejectInDryRun sends HTTP response in a typical go-appkit way when the rate limit is exceeded in the dry-run mode.

func DisableHTTPMetricsInContext added in v1.2.0

func DisableHTTPMetricsInContext(ctx context.Context)

DisableHTTPMetricsInContext disables HTTP metrics processing in the context.

func GetInternalRequestIDFromContext

func GetInternalRequestIDFromContext(ctx context.Context) string

GetInternalRequestIDFromContext extracts internal request id from the context.

func GetLoggerFromContext

func GetLoggerFromContext(ctx context.Context) log.FieldLogger

GetLoggerFromContext extracts logger from the context.

func GetRequestIDFromContext

func GetRequestIDFromContext(ctx context.Context) string

GetRequestIDFromContext extracts external request id from the context.

func GetRequestStartTimeFromContext

func GetRequestStartTimeFromContext(ctx context.Context) time.Time

GetRequestStartTimeFromContext extracts request start time from the context.

func GetRetryAfterEstimatedTime

func GetRetryAfterEstimatedTime(_ *http.Request, estimatedTime time.Duration) time.Duration

GetRetryAfterEstimatedTime returns estimated time after that the client may retry the request.

func GetTraceIDFromContext

func GetTraceIDFromContext(ctx context.Context) string

GetTraceIDFromContext extracts trace id from the context.

func HTTPRequestMetrics

func HTTPRequestMetrics(
	collector HTTPRequestMetricsCollector, getRoutePattern RoutePatternGetterFunc,
) func(next http.Handler) http.Handler

HTTPRequestMetrics is a middleware that collects metrics for incoming HTTP requests using Prometheus data types.

func HTTPRequestMetricsWithOpts

func HTTPRequestMetricsWithOpts(
	collector HTTPRequestMetricsCollector,
	getRoutePattern RoutePatternGetterFunc,
	opts HTTPRequestMetricsOpts,
) func(next http.Handler) http.Handler

HTTPRequestMetricsWithOpts is a more configurable version of HTTPRequestMetrics middleware.

func InFlightLimit

func InFlightLimit(limit int, errDomain string) (func(next http.Handler) http.Handler, error)

InFlightLimit is a middleware that limits the total number of currently served (in-flight) HTTP requests. It checks how many requests are in-flight and rejects with 503 if exceeded.

func InFlightLimitWithOpts

func InFlightLimitWithOpts(limit int, errDomain string, opts InFlightLimitOpts) (func(next http.Handler) http.Handler, error)

InFlightLimitWithOpts is a configurable version of a middleware to limit in-flight HTTP requests.

func IsHTTPMetricsEnabledInContext added in v1.2.0

func IsHTTPMetricsEnabledInContext(ctx context.Context) bool

IsHTTPMetricsEnabledInContext checks whether HTTP metrics are enabled in the context.

func Logging

func Logging(logger log.FieldLogger) func(next http.Handler) http.Handler

Logging is a middleware that logs info about HTTP request and response. Also, it puts logger (with external and internal request's ids in fields) into request's context.

func LoggingWithOpts

func LoggingWithOpts(logger log.FieldLogger, opts LoggingOpts) func(next http.Handler) http.Handler

LoggingWithOpts is a more configurable version of Logging middleware.

func MustInFlightLimit added in v1.3.0

func MustInFlightLimit(limit int, errDomain string) func(next http.Handler) http.Handler

MustInFlightLimit is a version of InFlightLimit that panics on error.

func MustInFlightLimitWithOpts added in v1.3.0

func MustInFlightLimitWithOpts(limit int, errDomain string, opts InFlightLimitOpts) func(next http.Handler) http.Handler

MustInFlightLimitWithOpts is a version of InFlightLimitWithOpts that panics on error.

func MustRateLimit added in v1.3.0

func MustRateLimit(maxRate Rate, errDomain string) func(next http.Handler) http.Handler

MustRateLimit is a version of RateLimit that panics if an error occurs.

func MustRateLimitWithOpts added in v1.3.0

func MustRateLimitWithOpts(maxRate Rate, errDomain string, opts RateLimitOpts) func(next http.Handler) http.Handler

MustRateLimitWithOpts is a version of RateLimitWithOpts that panics if an error occurs.

func NewContextWithHTTPMetricsEnabled added in v1.2.0

func NewContextWithHTTPMetricsEnabled(ctx context.Context) context.Context

NewContextWithHTTPMetricsEnabled creates a new context with special flag which can toggle HTTP metrics status.

func NewContextWithInternalRequestID

func NewContextWithInternalRequestID(ctx context.Context, internalRequestID string) context.Context

NewContextWithInternalRequestID creates a new context with internal request id.

func NewContextWithLogger

func NewContextWithLogger(ctx context.Context, logger log.FieldLogger) context.Context

NewContextWithLogger creates a new context with logger.

func NewContextWithLoggingParams

func NewContextWithLoggingParams(ctx context.Context, loggingParams *LoggingParams) context.Context

NewContextWithLoggingParams creates a new context with logging params.

func NewContextWithRequestID

func NewContextWithRequestID(ctx context.Context, requestID string) context.Context

NewContextWithRequestID creates a new context with external request id.

func NewContextWithRequestStartTime

func NewContextWithRequestStartTime(ctx context.Context, startTime time.Time) context.Context

NewContextWithRequestStartTime creates a new context with request start time.

func NewContextWithTraceID

func NewContextWithTraceID(ctx context.Context, traceID string) context.Context

NewContextWithTraceID creates a new context with trace id.

func RateLimit

func RateLimit(maxRate Rate, errDomain string) (func(next http.Handler) http.Handler, error)

RateLimit is a middleware that limits the rate of HTTP requests.

func RateLimitWithOpts

func RateLimitWithOpts(maxRate Rate, errDomain string, opts RateLimitOpts) (func(next http.Handler) http.Handler, error)

RateLimitWithOpts is a configurable version of a middleware to limit the rate of HTTP requests.

func Recovery

func Recovery(errDomain string) func(next http.Handler) http.Handler

Recovery is a middleware that recovers from panics, logs the panic value and a stacktrace, returns 500 HTTP status code and error in body in right format.

func RecoveryWithOpts

func RecoveryWithOpts(errDomain string, opts RecoveryOpts) func(next http.Handler) http.Handler

RecoveryWithOpts is a more configurable version of Recovery middleware.

func RequestBodyLimit

func RequestBodyLimit(maxSizeBytes uint64, errDomain string) func(next http.Handler) http.Handler

RequestBodyLimit is a middleware that sets the maximum allowed size for a request body. The body limit is determined based on both Content-Length request header and actual content read. Such limiting helps to prevent the server resources being wasted if a malicious client sends a very large request body.

func RequestID

func RequestID() func(next http.Handler) http.Handler

RequestID is a middleware that reads value of X-Request-ID request's HTTP header and generates new one if it's empty. Also, the middleware generates yet another id which may be used for internal purposes. The first id is named external request id, the second one - internal request id. Both these ids are put into request's context and returned in HTTP response in X-Request-ID and X-Int-Request-ID headers. It's using xid (based on Mongo Object ID algorithm). This ID generator has high performance with pretty enough entropy.

func RequestIDWithOpts

func RequestIDWithOpts(opts RequestIDOpts) func(next http.Handler) http.Handler

RequestIDWithOpts is a more configurable version of RequestID middleware.

Types

type CustomLoggerProvider

type CustomLoggerProvider func(r *http.Request) log.FieldLogger

CustomLoggerProvider returns a custom logger or nil based on the request.

type HTTPRequestInfoMetrics added in v1.3.0

type HTTPRequestInfoMetrics struct {
	Method        string
	RoutePattern  string
	UserAgentType string
}

HTTPRequestInfoMetrics represents a request info for collecting metrics.

type HTTPRequestMetricsCollector

type HTTPRequestMetricsCollector interface {
	// IncInFlightRequests increments the counter of in-flight requests.
	IncInFlightRequests(requestInfo HTTPRequestInfoMetrics)

	// DecInFlightRequests decrements the counter of in-flight requests.
	DecInFlightRequests(requestInfo HTTPRequestInfoMetrics)

	// ObserveRequestFinish observes the duration of the request and the status code.
	ObserveRequestFinish(requestInfo HTTPRequestInfoMetrics, status int, startTime time.Time)
}

HTTPRequestMetricsCollector is an interface for collecting metrics for incoming HTTP requests.

type HTTPRequestMetricsOpts

type HTTPRequestMetricsOpts struct {
	GetUserAgentType  UserAgentTypeGetterFunc
	ExcludedEndpoints []string
}

HTTPRequestMetricsOpts represents an options for HTTPRequestMetrics middleware.

type HTTPRequestPrometheusMetrics added in v1.3.0

type HTTPRequestPrometheusMetrics struct {
	Durations *prometheus.HistogramVec
	InFlight  *prometheus.GaugeVec
}

HTTPRequestPrometheusMetrics represents collector of metrics for incoming HTTP requests.

func NewHTTPRequestPrometheusMetrics added in v1.3.0

func NewHTTPRequestPrometheusMetrics() *HTTPRequestPrometheusMetrics

NewHTTPRequestPrometheusMetrics creates a new instance of HTTPRequestPrometheusMetrics with default options.

func NewHTTPRequestPrometheusMetricsWithOpts added in v1.3.0

func NewHTTPRequestPrometheusMetricsWithOpts(opts HTTPRequestPrometheusMetricsOpts) *HTTPRequestPrometheusMetrics

NewHTTPRequestPrometheusMetricsWithOpts creates a new instance of HTTPRequestPrometheusMetrics with the provided options.

func (*HTTPRequestPrometheusMetrics) DecInFlightRequests added in v1.3.0

func (pm *HTTPRequestPrometheusMetrics) DecInFlightRequests(requestInfo HTTPRequestInfoMetrics)

DecInFlightRequests decrements the counter of in-flight requests.

func (*HTTPRequestPrometheusMetrics) IncInFlightRequests added in v1.3.0

func (pm *HTTPRequestPrometheusMetrics) IncInFlightRequests(requestInfo HTTPRequestInfoMetrics)

IncInFlightRequests increments the counter of in-flight requests.

func (*HTTPRequestPrometheusMetrics) MustCurryWith added in v1.3.0

MustCurryWith curries the metrics collector with the provided labels.

func (*HTTPRequestPrometheusMetrics) MustRegister added in v1.3.0

func (pm *HTTPRequestPrometheusMetrics) MustRegister()

MustRegister does registration of metrics collector in Prometheus and panics if any error occurs.

func (*HTTPRequestPrometheusMetrics) ObserveRequestFinish added in v1.3.0

func (pm *HTTPRequestPrometheusMetrics) ObserveRequestFinish(
	requestInfo HTTPRequestInfoMetrics, status int, startTime time.Time,
)

ObserveRequestFinish observes the duration of the request and the status code.

func (*HTTPRequestPrometheusMetrics) Unregister added in v1.3.0

func (pm *HTTPRequestPrometheusMetrics) Unregister()

Unregister cancels registration of metrics collector in Prometheus.

type HTTPRequestPrometheusMetricsOpts added in v1.3.0

type HTTPRequestPrometheusMetricsOpts struct {
	// Namespace is a namespace for metrics. It will be prepended to all metric names.
	Namespace string

	// DurationBuckets is a list of buckets into which observations of serving HTTP requests are counted.
	DurationBuckets []float64

	// ConstLabels is a set of labels that will be applied to all metrics.
	ConstLabels prometheus.Labels

	// CurriedLabelNames is a list of label names that will be curried with the provided labels.
	// See HTTPRequestPrometheusMetrics.MustCurryWith method for more details.
	// Keep in mind that if this list is not empty,
	// HTTPRequestPrometheusMetrics.MustCurryWith method must be called further with the same labels.
	// Otherwise, the collector will panic.
	CurriedLabelNames []string
}

HTTPRequestPrometheusMetricsOpts represents an options for HTTPRequestPrometheusMetrics.

type InFlightLimitGetKeyFunc

type InFlightLimitGetKeyFunc func(r *http.Request) (key string, bypass bool, err error)

InFlightLimitGetKeyFunc is a function that is called for getting key for in-flight limiting.

type InFlightLimitGetRetryAfterFunc

type InFlightLimitGetRetryAfterFunc func(r *http.Request) time.Duration

InFlightLimitGetRetryAfterFunc is a function that is called to get a value for Retry-After response HTTP header when the in-flight limit is exceeded.

type InFlightLimitOnErrorFunc

type InFlightLimitOnErrorFunc func(rw http.ResponseWriter, r *http.Request,
	params InFlightLimitParams, err error, next http.Handler, logger log.FieldLogger)

InFlightLimitOnErrorFunc is a function that is called in case of any error that may occur during the in-flight limiting.

type InFlightLimitOnRejectFunc

type InFlightLimitOnRejectFunc func(rw http.ResponseWriter, r *http.Request,
	params InFlightLimitParams, next http.Handler, logger log.FieldLogger)

InFlightLimitOnRejectFunc is a function that is called for rejecting HTTP request when the in-flight limit is exceeded.

type InFlightLimitOpts

type InFlightLimitOpts struct {
	GetKey             InFlightLimitGetKeyFunc
	MaxKeys            int
	ResponseStatusCode int
	GetRetryAfter      InFlightLimitGetRetryAfterFunc
	BacklogLimit       int
	BacklogTimeout     time.Duration
	DryRun             bool

	OnReject         InFlightLimitOnRejectFunc
	OnRejectInDryRun InFlightLimitOnRejectFunc
	OnError          InFlightLimitOnErrorFunc
}

InFlightLimitOpts represents an options for the middleware to limit in-flight HTTP requests.

type InFlightLimitParams

type InFlightLimitParams struct {
	ResponseStatusCode int
	GetRetryAfter      InFlightLimitGetRetryAfterFunc
	ErrDomain          string
	Key                string
	RequestBacklogged  bool
}

InFlightLimitParams contains data that relates to the in-flight limiting procedure and could be used for rejecting or handling an occurred error.

type LoggingOpts

type LoggingOpts struct {
	RequestStart           bool
	RequestHeaders         map[string]string
	ExcludedEndpoints      []string
	SecretQueryParams      []string
	AddRequestInfoToLogger bool
	SlowRequestThreshold   time.Duration // controls when to include "time_slots" field group into final log message
	// If CustomLoggerProvider is not set or returns nil, loggingHandler.logger will be used.
	CustomLoggerProvider CustomLoggerProvider
}

LoggingOpts represents an options for Logging middleware.

type LoggingParams

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

LoggingParams stores parameters for the Logging middleware that may be modified dynamically by the other underlying middlewares/handlers.

func GetLoggingParamsFromContext

func GetLoggingParamsFromContext(ctx context.Context) *LoggingParams

GetLoggingParamsFromContext extracts logging params from the context.

func (*LoggingParams) AddTimeSlotDurationInMs

func (lp *LoggingParams) AddTimeSlotDurationInMs(name string, dur time.Duration)

AddTimeSlotDurationInMs sets (if new) or adds duration value in milliseconds to the element of the time_slots map

func (*LoggingParams) AddTimeSlotInt

func (lp *LoggingParams) AddTimeSlotInt(name string, dur int64)

AddTimeSlotInt sets (if new) or adds duration value to the element of the time_slots map

func (*LoggingParams) ExtendFields

func (lp *LoggingParams) ExtendFields(fields ...log.Field)

ExtendFields extends list of fields that will be logged by the Logging middleware.

type Rate

type Rate struct {
	Count    int
	Duration time.Duration
}

Rate describes the frequency of requests.

type RateLimitAlg

type RateLimitAlg int

RateLimitAlg represents a type for specifying rate-limiting algorithm.

const (
	RateLimitAlgLeakyBucket RateLimitAlg = iota
	RateLimitAlgSlidingWindow
)

Supported rate-limiting algorithms.

type RateLimitGetKeyFunc

type RateLimitGetKeyFunc func(r *http.Request) (key string, bypass bool, err error)

RateLimitGetKeyFunc is a function that is called for getting key for rate limiting.

type RateLimitGetRetryAfterFunc

type RateLimitGetRetryAfterFunc func(r *http.Request, estimatedTime time.Duration) time.Duration

RateLimitGetRetryAfterFunc is a function that is called to get a value for Retry-After response HTTP header when the rate limit is exceeded.

type RateLimitOnErrorFunc

type RateLimitOnErrorFunc func(rw http.ResponseWriter, r *http.Request,
	params RateLimitParams, err error, next http.Handler, logger log.FieldLogger)

RateLimitOnErrorFunc is a function that is called for rejecting HTTP request when the rate limit is exceeded.

type RateLimitOnRejectFunc

type RateLimitOnRejectFunc func(rw http.ResponseWriter, r *http.Request,
	params RateLimitParams, next http.Handler, logger log.FieldLogger)

RateLimitOnRejectFunc is a function that is called for rejecting HTTP request when the rate limit is exceeded.

type RateLimitOpts

type RateLimitOpts struct {
	Alg                RateLimitAlg
	MaxBurst           int
	GetKey             RateLimitGetKeyFunc
	MaxKeys            int
	ResponseStatusCode int
	GetRetryAfter      RateLimitGetRetryAfterFunc
	DryRun             bool
	BacklogLimit       int
	BacklogTimeout     time.Duration

	OnReject         RateLimitOnRejectFunc
	OnRejectInDryRun RateLimitOnRejectFunc
	OnError          RateLimitOnErrorFunc
}

RateLimitOpts represents an options for the RateLimit middleware.

type RateLimitParams

type RateLimitParams struct {
	ErrDomain           string
	ResponseStatusCode  int
	GetRetryAfter       RateLimitGetRetryAfterFunc
	Key                 string
	RequestBacklogged   bool
	EstimatedRetryAfter time.Duration
}

RateLimitParams contains data that relates to the rate limiting procedure and could be used for rejecting or handling an occurred error.

type RecoveryOpts

type RecoveryOpts struct {
	StackSize int
}

RecoveryOpts represents an options for Recovery middleware.

type RequestIDOpts

type RequestIDOpts struct {
	GenerateID         func() string
	GenerateInternalID func() string
}

RequestIDOpts represents an options for RequestID middleware.

type RoutePatternGetterFunc

type RoutePatternGetterFunc func(r *http.Request) string

RoutePatternGetterFunc is a function for getting route pattern from the request. Used in multiple middlewares.

Usually it depends on the router that is used in HTTP server:

func getGorillaMuxRoutePattern(r *http.Request) string {
	curRoute := mux.CurrentRoute(r)
	if curRoute == nil {
		return ""
	}
	pathTemplate, err := curRoute.GetPathTemplate()
	if err != nil {
		return ""
	}
	return pathTemplate
}

func getChiRoutePattern(r *http.Request) string {
	ctxVal := r.Context().Value(chi.RouteCtxKey)
	if ctxVal == nil {
		return ""
	}
	chiCtx := ctxVal.(*chi.Context)
	if chiCtx == nil {
		return ""
	}
	return chiCtx.RoutePattern()
}

type UserAgentTypeGetterFunc

type UserAgentTypeGetterFunc func(r *http.Request) string

UserAgentTypeGetterFunc is a function for getting user agent type from the request. The set of return values must be finite.

type WrapResponseWriter

type WrapResponseWriter interface {
	http.ResponseWriter
	// Status returns the HTTP status of the request, or 0 if one has not
	// yet been sent.
	Status() int
	// BytesWritten returns the total number of bytes sent to the client.
	BytesWritten() int
	// ElapsedTime returns the time spent recording the response.
	ElapsedTime() time.Duration
	// Tee causes the response body to be written to the given io.Writer in
	// addition to proxying the writes through. Only one io.Writer can be
	// tee'd to at once: setting a second one will overwrite the first.
	// Writes will be sent to the proxy before being written to this
	// io.Writer. It is illegal for the tee'd writer to be modified
	// concurrently with writes.
	Tee(io.Writer)
	// Unwrap returns the original proxied target.
	Unwrap() http.ResponseWriter
	// Discard causes all writes to the original ResponseWriter be discarded,
	// instead writing only to the tee'd writer if it's set.
	// The caller is responsible for calling WriteHeader and Write on the
	// original ResponseWriter once the processing is done.
	Discard()
}

WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook into various parts of the response process.

func NewWrapResponseWriter

func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter

NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to hook into various parts of the response process.

func WrapResponseWriterIfNeeded

func WrapResponseWriterIfNeeded(rw http.ResponseWriter, protoMajor int) WrapResponseWriter

WrapResponseWriterIfNeeded wraps an http.ResponseWriter (if it is not already wrapped), returning a proxy that allows you to hook into various parts of the response process.

Directories

Path Synopsis
Package throttle provides configurable middleware for throttling HTTP requests on the server side.
Package throttle provides configurable middleware for throttling HTTP requests on the server side.

Jump to

Keyboard shortcuts

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