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 ¶
- Constants
- Variables
- func DefaultInFlightLimitOnError(rw http.ResponseWriter, r *http.Request, params InFlightLimitParams, err error, ...)
- func DefaultInFlightLimitOnReject(rw http.ResponseWriter, r *http.Request, params InFlightLimitParams, ...)
- func DefaultInFlightLimitOnRejectInDryRun(rw http.ResponseWriter, r *http.Request, params InFlightLimitParams, ...)
- func DefaultRateLimitOnError(rw http.ResponseWriter, r *http.Request, params RateLimitParams, err error, ...)
- func DefaultRateLimitOnReject(rw http.ResponseWriter, r *http.Request, params RateLimitParams, ...)
- func DefaultRateLimitOnRejectInDryRun(rw http.ResponseWriter, r *http.Request, params RateLimitParams, ...)
- func DisableHTTPMetricsInContext(ctx context.Context)
- func GetInternalRequestIDFromContext(ctx context.Context) string
- func GetLoggerFromContext(ctx context.Context) log.FieldLogger
- func GetRequestIDFromContext(ctx context.Context) string
- func GetRequestStartTimeFromContext(ctx context.Context) time.Time
- func GetRetryAfterEstimatedTime(_ *http.Request, estimatedTime time.Duration) time.Duration
- func GetTraceIDFromContext(ctx context.Context) string
- func HTTPRequestMetrics(collector HTTPRequestMetricsCollector, getRoutePattern RoutePatternGetterFunc) func(next http.Handler) http.Handler
- func HTTPRequestMetricsWithOpts(collector HTTPRequestMetricsCollector, getRoutePattern RoutePatternGetterFunc, ...) func(next http.Handler) http.Handler
- func InFlightLimit(limit int, errDomain string) (func(next http.Handler) http.Handler, error)
- func InFlightLimitWithOpts(limit int, errDomain string, opts InFlightLimitOpts) (func(next http.Handler) http.Handler, error)
- func IsHTTPMetricsEnabledInContext(ctx context.Context) bool
- func Logging(logger log.FieldLogger) func(next http.Handler) http.Handler
- func LoggingWithOpts(logger log.FieldLogger, opts LoggingOpts) func(next http.Handler) http.Handler
- func MustInFlightLimit(limit int, errDomain string) func(next http.Handler) http.Handler
- func MustInFlightLimitWithOpts(limit int, errDomain string, opts InFlightLimitOpts) func(next http.Handler) http.Handler
- func MustRateLimit(maxRate Rate, errDomain string) func(next http.Handler) http.Handler
- func MustRateLimitWithOpts(maxRate Rate, errDomain string, opts RateLimitOpts) func(next http.Handler) http.Handler
- func NewContextWithHTTPMetricsEnabled(ctx context.Context) context.Context
- func NewContextWithInternalRequestID(ctx context.Context, internalRequestID string) context.Context
- func NewContextWithLogger(ctx context.Context, logger log.FieldLogger) context.Context
- func NewContextWithLoggingParams(ctx context.Context, loggingParams *LoggingParams) context.Context
- func NewContextWithRequestID(ctx context.Context, requestID string) context.Context
- func NewContextWithRequestStartTime(ctx context.Context, startTime time.Time) context.Context
- func NewContextWithTraceID(ctx context.Context, traceID string) context.Context
- func RateLimit(maxRate Rate, errDomain string) (func(next http.Handler) http.Handler, error)
- func RateLimitWithOpts(maxRate Rate, errDomain string, opts RateLimitOpts) (func(next http.Handler) http.Handler, error)
- func Recovery(errDomain string) func(next http.Handler) http.Handler
- func RecoveryWithOpts(errDomain string, opts RecoveryOpts) func(next http.Handler) http.Handler
- func RequestBodyLimit(maxSizeBytes uint64, errDomain string) func(next http.Handler) http.Handler
- func RequestID() func(next http.Handler) http.Handler
- func RequestIDWithOpts(opts RequestIDOpts) func(next http.Handler) http.Handler
- type CustomLoggerProvider
- type HTTPRequestInfoMetrics
- type HTTPRequestMetricsCollector
- type HTTPRequestMetricsOpts
- type HTTPRequestPrometheusMetrics
- func (pm *HTTPRequestPrometheusMetrics) DecInFlightRequests(requestInfo HTTPRequestInfoMetrics)
- func (pm *HTTPRequestPrometheusMetrics) IncInFlightRequests(requestInfo HTTPRequestInfoMetrics)
- func (pm *HTTPRequestPrometheusMetrics) MustCurryWith(labels prometheus.Labels) *HTTPRequestPrometheusMetrics
- func (pm *HTTPRequestPrometheusMetrics) MustRegister()
- func (pm *HTTPRequestPrometheusMetrics) ObserveRequestFinish(requestInfo HTTPRequestInfoMetrics, status int, startTime time.Time)
- func (pm *HTTPRequestPrometheusMetrics) Unregister()
- type HTTPRequestPrometheusMetricsOpts
- type InFlightLimitGetKeyFunc
- type InFlightLimitGetRetryAfterFunc
- type InFlightLimitOnErrorFunc
- type InFlightLimitOnRejectFunc
- type InFlightLimitOpts
- type InFlightLimitParams
- type LoggingOpts
- type LoggingParams
- type Rate
- type RateLimitAlg
- type RateLimitGetKeyFunc
- type RateLimitGetRetryAfterFunc
- type RateLimitOnErrorFunc
- type RateLimitOnRejectFunc
- type RateLimitOpts
- type RateLimitParams
- type RecoveryOpts
- type RequestIDOpts
- type RoutePatternGetterFunc
- type UserAgentTypeGetterFunc
- type WrapResponseWriter
Examples ¶
Constants ¶
const ( InFlightLimitLogFieldKey = "in_flight_limit_key" InFlightLimitLogFieldBacklogged = "in_flight_limit_backlogged" )
Log fields for InFlightLimit middleware.
const DefaultInFlightLimitBacklogTimeout = time.Second * 5
DefaultInFlightLimitBacklogTimeout determines how long the HTTP request may be in the backlog status.
const DefaultInFlightLimitMaxKeys = 10000
DefaultInFlightLimitMaxKeys is a default value of maximum keys number for the InFlightLimit middleware.
const DefaultRateLimitBacklogTimeout = time.Second * 5
DefaultRateLimitBacklogTimeout determines how long the HTTP request may be in the backlog status.
const DefaultRateLimitMaxKeys = 10000
DefaultRateLimitMaxKeys is a default value of maximum keys number for the RateLimit middleware.
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.
const (
// LoggingSecretQueryPlaceholder represents a placeholder that will be used for secret query parameters.
LoggingSecretQueryPlaceholder = "_HIDDEN_"
)
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.
const RateLimitLogFieldKey = "rate_limit_key"
RateLimitLogFieldKey it is the name of the logged field that contains a key for the requests rate limiter.
const RecoveryDefaultStackSize = 8192
RecoveryDefaultStackSize defines the default size of stack part which will be logged.
Variables ¶
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
DisableHTTPMetricsInContext disables HTTP metrics processing in the context.
func GetInternalRequestIDFromContext ¶
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 ¶
GetRequestIDFromContext extracts external request id from the context.
func GetRequestStartTimeFromContext ¶
GetRequestStartTimeFromContext extracts request start time from the context.
func GetRetryAfterEstimatedTime ¶
GetRetryAfterEstimatedTime returns estimated time after that the client may retry the request.
func GetTraceIDFromContext ¶
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 ¶
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
IsHTTPMetricsEnabledInContext checks whether HTTP metrics are enabled in the context.
func Logging ¶
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
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
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
NewContextWithHTTPMetricsEnabled creates a new context with special flag which can toggle HTTP metrics status.
func NewContextWithInternalRequestID ¶
NewContextWithInternalRequestID creates a new context with internal request id.
func NewContextWithLogger ¶
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 ¶
NewContextWithRequestID creates a new context with external request id.
func NewContextWithRequestStartTime ¶
NewContextWithRequestStartTime creates a new context with request start time.
func NewContextWithTraceID ¶
NewContextWithTraceID creates a new context with trace id.
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 ¶
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 ¶
RecoveryWithOpts is a more configurable version of Recovery middleware.
func RequestBodyLimit ¶
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 ¶
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
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
func (pm *HTTPRequestPrometheusMetrics) MustCurryWith(labels prometheus.Labels) *HTTPRequestPrometheusMetrics
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 ¶
InFlightLimitGetKeyFunc is a function that is called for getting key for in-flight limiting.
type InFlightLimitGetRetryAfterFunc ¶
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 RateLimitAlg ¶
type RateLimitAlg int
RateLimitAlg represents a type for specifying rate-limiting algorithm.
const ( RateLimitAlgLeakyBucket RateLimitAlg = iota RateLimitAlgSlidingWindow )
Supported rate-limiting algorithms.
type RateLimitGetKeyFunc ¶
RateLimitGetKeyFunc is a function that is called for getting key for rate limiting.
type RateLimitGetRetryAfterFunc ¶
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 ¶
RequestIDOpts represents an options for RequestID middleware.
type RoutePatternGetterFunc ¶
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 ¶
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.