### GorestfulMiddleware Example Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/gorestful Demonstrates how to create a default middleware factory and use it to generate Gorestful compatible middleware. ```go package main import ( "net/http" "github.com/slok/go-http-metrics/middleware" "github.com/slok/go-http-metrics/middleware/gorestful" ) func main() { // Create a default middleware factory. // You can configure it with custom metrics, labels, etc. metricMWFactory := middleware.NewFactory(middleware.FactoryConfig{}) // Create a Gorestful compatible middleware from the factory. goreMW := gorestful.NewMiddleware(gorestful.Config{ Middleware: metricMWFactory.MustNew(middleware.Config{}), }) // Use the goreMW as a gorestful.FilterFunction. http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Your application logic here. w.Write([]byte("Hello, World!")) })) } ``` -------------------------------- ### Getting Started with Prometheus and Go http.Handler Source: https://pkg.go.dev/github.com/slok/go-http-metrics A basic example demonstrating how to use go-http-metrics with Prometheus as the metrics recorder and the standard Go http.Handler. It sets up middleware to record metrics and serves them via promhttp.Handler. ```go package main import ( "log" "net/http" "github.com/prometheus/client_golang/prometheus/promhttp" metrics "github.com/slok/go-http-metrics/metrics/prometheus" "github.com/slok/go-http-metrics/middleware" middlewarestd "github.com/slok/go-http-metrics/middleware/std" ) func main() { // Create our middleware. mdlw := middleware.New(middleware.Config{ Recorder: metrics.NewRecorder(metrics.Config{}), }) // Our handler. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("hello world!")) }) h = middlewarestd.Handler("", mdlw, h) // Serve metrics. log.Printf("serving metrics at: %s", ":9090") go http.ListenAndServe(":9090", promhttp.Handler()) // Serve our handler. log.Printf("listening at: %s", ":8080") if err := http.ListenAndServe(":8080", h); err != nil { log.Panicf("error while serving: %s", err) } } ``` -------------------------------- ### HTTPRouterMiddlewareOnRouter Example Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/httprouter Demonstrates creating a default middleware factory and using it to wrap an httprouter Router. ```go package main import ( "net/http" "github.com/julienschmidt/httprouter" "github.com/slok/go-http-metrics/middleware" "github.com/slok/go-http-metrics/middleware/httprouter" ) func main() { // Create a new middleware factory. m := middleware.New(middleware.Config{}) // Create a httprouter compatible middleware factory. h := httprouter.New( httprouter.Config{}, ) // Create a new httprouter router. router := httprouter.New() // Wrap the router with the httprouter middleware. router.GET("/", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // Your httprouter handler logic here. w.WriteHeader(http.StatusOK) w.Write([]byte("Hello, World!")) }) wrappedRouter := h.WrapRouter(router) // Start the server. http.ListenAndServe(":8080", wrappedRouter) } ``` -------------------------------- ### HTTPRouterMiddlewareByHandler Example Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/httprouter Shows how to create a default middleware factory and use it to set up httprouter compatible middleware by handler. ```go package main import ( "net/http" "github.com/julienschmidt/httprouter" "github.com/slok/go-http-metrics/middleware" "github.com/slok/go-http-metrics/middleware/httprouter" ) func main() { // Create a new middleware factory. m := middleware.New(middleware.Config{}) // Create a httprouter compatible middleware factory. h := httprouter.New( httprouter.Config{}, ) // Create a httprouter handler. var handler httprouter.Handle handler = h.WrapHandle(func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // Your httprouter handler logic here. w.WriteHeader(http.StatusOK) w.Write([]byte("Hello, World!")) }) // Create a new httprouter router. router := httprouter.New() // Register the handler. router.GET("/", handler) // Start the server. http.ListenAndServe(":8080", router) } ``` -------------------------------- ### Create Prometheus Metrics Middleware for Standard Go HTTP Source: https://pkg.go.dev/github.com/slok/go-http-metrics This example demonstrates how to create and use Prometheus metrics middleware with the standard Go net/http handler. It sets up a recorder and applies the middleware to a custom handler, also serving Prometheus metrics on a separate port. ```go package main import ( "log" "net/http" "github.com/prometheus/client_golang/prometheus/promhttp" httpmetrics "github.com/slok/go-http-metrics/metrics/prometheus" httpmiddleware "github.com/slok/go-http-metrics/middleware" httpstdmiddleware "github.com/slok/go-http-metrics/middleware/std" ) func main() { // Create our middleware. mdlw := httpmiddleware.New(httpmiddleware.Config{ Recorder: httpmetrics.NewRecorder(httpmetrics.Config{}), }) // Our handler. myHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("hello world!")) }) h := httpstdmiddleware.Handler("", mdlw, myHandler) // Serve metrics. log.Printf("serving metrics at: %s", ":9090") go http.ListenAndServe(":9090", promhttp.Handler()) // Serve our handler. log.Printf("listening at: %s", ":8080") if err := http.ListenAndServe(":8080", h); err != nil { log.Panicf("error while serving: %s", err) } } ``` -------------------------------- ### New Middleware service constructor Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware Creates and returns a new Middleware service with the provided configuration. ```go func New(cfg Config) Middleware ``` -------------------------------- ### GojiMiddleware Factory Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/goji Shows how to create a default middleware factory and use it to create a Goji compatible middleware. ```go func Handler(handlerID string, m middleware.Middleware) func(http.Handler) http.Handler ``` -------------------------------- ### Create OpenCensus Recorder Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics/opencensus Use `NewRecorder` to create a new metrics recorder that uses OpenCensus stats as the backend. Configuration options are available via the `Config` struct. ```go func NewRecorder(cfg Config) (metrics.Recorder, error) ``` -------------------------------- ### Config struct for middleware options Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware Defines configuration options for the middleware, including the metrics recorder, service identifier, status code grouping, and disabling of size/inflight measurements. Use IgnoredPaths to exclude specific routes from duration and size metrics. ```go type Config struct { // Recorder is the way the metrics will be recorder in the different backends. Recorder metrics.Recorder // Service is an optional identifier for the metrics, this can be useful if // a same service has multiple servers (e.g API, metrics and healthchecks). Service string // GroupedStatus will group the status label in the form of `\dxx`, for example, // 200, 201, and 203 will have the label `code="2xx"`. This impacts on the cardinality // of the metrics and also improves the performance of queries that are grouped by // status code because there are already aggregated in the metric. // By default will be false. GroupedStatus bool // DisableMeasureSize will disable the recording metrics about the response size, // by default measuring size is enabled (`DisableMeasureSize` is false). DisableMeasureSize bool // DisableMeasureInflight will disable the recording metrics about the inflight requests number, // by default measuring inflights is enabled (`DisableMeasureInflight` is false). DisableMeasureInflight bool // IgnoredPaths is a list of paths that will not be measured for the request duration // and the response size. They will still be counted in the RequestsInflight metric. IgnoredPaths []string } ``` -------------------------------- ### OpenCensus Recorder Configuration Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics/opencensus The `Config` struct allows customization of metric collection for HTTP requests. You can define custom buckets for duration and size, and specify label names for handler ID, status code, method, and service. ```go type Config struct { // DurationBuckets are the buckets used for the HTTP request duration metrics, // by default uses default buckets (from 5ms to 10s). DurationBuckets []float64 // SizeBuckets are the buckets for the HTTP response size metrics, // by default uses a exponential buckets from 100B to 1GB. SizeBuckets []float64 // HandlerIDLabel is the name that will be set to the handler ID label, by default is `handler`. HandlerIDLabel string // StatusCodeLabel is the name that will be set to the status code label, by default is `code`. StatusCodeLabel string // MethodLabel is the name that will be set to the method label, by default is `method`. MethodLabel string // ServiceLabel is the name that will be set to the service label, by default is `service`. ServiceLabel string // UnregisterViewsBeforeRegister will unregister the previous Recorder views before registering again. This is required on cases where multiple instances of recorder will be made due to how // Opencensus is implemented (everything is at global state). Sadly this option is a kind of hack // so we can test without exposing the views to the user. On regular usage this option is very rare to use it. UnregisterViewsBeforeRegister bool } ``` -------------------------------- ### Mock AddInflightRequests Method Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/metrics Provides a mock implementation for the AddInflightRequests method. Use this to simulate adding inflight requests in tests, specifying context, properties, and quantity. ```go func (_m *Recorder) AddInflightRequests(ctx context.Context, props metrics.HTTPProperties, quantity int) ``` -------------------------------- ### Measure HTTP handler with reporter Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware Wraps an HTTP handler to measure its performance using a Reporter. It calls the provided `next` function to execute the handler's logic before and after measurement. ```go func (m Middleware) Measure(handlerID string, reporter Reporter, next func()) ``` -------------------------------- ### Mock ObserveHTTPResponseSize Method Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/metrics Provides a mock implementation for the ObserveHTTPResponseSize method. Use this to simulate observing the size of HTTP responses in tests, specifying context, properties, and size in bytes. ```go func (_m *Recorder) ObserveHTTPResponseSize(ctx context.Context, props metrics.HTTPReqProperties, sizeBytes int64) ``` -------------------------------- ### New Prometheus Recorder Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics/prometheus Creates a new Prometheus metrics recorder. Configure options like metric prefix, buckets, and Prometheus registry. ```go func NewRecorder(cfg Config) metrics.Recorder ``` -------------------------------- ### Config Struct Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics/opencensus Configuration options for the OpenCensus metrics recorder, allowing customization of buckets, label names, and view registration behavior. ```APIDOC ## type Config ### Description Config has the dependencies and values of the recorder. ### Fields - **DurationBuckets** ([]float64) - The buckets used for the HTTP request duration metrics. Defaults to exponential buckets from 5ms to 10s. - **SizeBuckets** ([]float64) - The buckets for the HTTP response size metrics. Defaults to exponential buckets from 100B to 1GB. - **HandlerIDLabel** (string) - The name for the handler ID label. Defaults to `handler`. - **StatusCodeLabel** (string) - The name for the status code label. Defaults to `code`. - **MethodLabel** (string) - The name for the method label. Defaults to `method`. - **ServiceLabel** (string) - The name for the service label. Defaults to `service`. - **UnregisterViewsBeforeRegister** (bool) - If true, unregisters previous Recorder views before registering again. This is a workaround for OpenCensus's global state and is rarely needed in regular usage. ``` -------------------------------- ### Reporter Context Method Mock Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/middleware Provides a mock function for the Context method of the Reporter type. ```go func (_m *Reporter) Context() context.Context ``` -------------------------------- ### NewRecorder Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics/prometheus Creates a new Prometheus metrics recorder. It takes a Config struct to customize its behavior, such as setting metric prefixes, duration/size buckets, and Prometheus registry. ```APIDOC ## func NewRecorder ### Description NewRecorder returns a new metrics recorder that implements the recorder using Prometheus as the backend. ### Signature ```go func NewRecorder(cfg Config) metrics.Recorder ``` ### Parameters #### Parameters - **cfg** (Config) - Required - Configuration for the Prometheus recorder. ``` -------------------------------- ### NewRecorder Function Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics/opencensus Creates a new metrics recorder that utilizes OpenCensus stats as its backend. It takes a `Config` struct to customize its behavior. ```APIDOC ## func NewRecorder ### Description NewRecorder returns a new Recorder that uses OpenCensus stats as the backend. ### Signature ```go func NewRecorder(cfg Config) (metrics.Recorder, error) ``` ### Parameters #### Parameters - **cfg** (Config) - The configuration for the new recorder. ``` -------------------------------- ### HandlerProvider function signature Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/std Returns a handler provider, which is a common pattern in web frameworks. Use this to create middleware factories. ```go func HandlerProvider(handlerID string, m middleware.Middleware) func(http.Handler) http.Handler ``` -------------------------------- ### Mock ObserveHTTPRequestDuration Method Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/metrics Provides a mock implementation for the ObserveHTTPRequestDuration method. Use this to simulate observing the duration of HTTP requests in tests, specifying context, properties, and duration. ```go func (_m *Recorder) ObserveHTTPRequestDuration(ctx context.Context, props metrics.HTTPReqProperties, duration time.Duration) ``` -------------------------------- ### Reporter URLPath Method Mock Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/middleware Provides a mock function for the URLPath method of the Reporter type. ```go func (_m *Reporter) URLPath() string ``` -------------------------------- ### Dummy Constant Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics Dummy is a dummy recorder. ```APIDOC ## Constant: Dummy Dummy is a dummy recorder. ``` -------------------------------- ### Prometheus Recorder Configuration Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics/prometheus Defines the configuration for the Prometheus metrics recorder. Customize labels, buckets, and the Prometheus registry. ```go type Config struct { // Prefix is the prefix that will be set on the metrics, by default it will be empty. Prefix string // DurationBuckets are the buckets used by Prometheus for the HTTP request duration metrics, // by default uses Prometheus default buckets (from 5ms to 10s). DurationBuckets []float64 // SizeBuckets are the buckets used by Prometheus for the HTTP response size metrics, // by default uses a exponential buckets from 100B to 1GB. SizeBuckets []float64 // Registry is the registry that will be used by the recorder to store the metrics, // if the default registry is not used then it will use the default one. Registry prometheus.Registerer // HandlerIDLabel is the name that will be set to the handler ID label, by default is `handler`. HandlerIDLabel string // StatusCodeLabel is the name that will be set to the status code label, by default is `code`. StatusCodeLabel string // MethodLabel is the name that will be set to the method label, by default is `method`. MethodLabel string // ServiceLabel is the name that will be set to the service label, by default is `service`. ServiceLabel string } ``` -------------------------------- ### Reporter Method Mock Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/middleware Provides a mock function for the Method method of the Reporter type. ```go func (_m *Reporter) Method() string ``` -------------------------------- ### Dummy Recorder Constant Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics Defines a dummy recorder for testing or scenarios where metrics are not actively collected. ```go const Dummy = dummy(0) ``` -------------------------------- ### Config Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics/prometheus Configuration struct for the Prometheus metrics recorder. It allows customization of metric prefixes, buckets, and labels. ```APIDOC ## type Config ### Description Config has the dependencies and values of the recorder. ### Fields - **Prefix** (string) - Optional - The prefix that will be set on the metrics, by default it will be empty. - **DurationBuckets** ([]float64) - Optional - The buckets used by Prometheus for the HTTP request duration metrics, by default uses Prometheus default buckets (from 5ms to 10s). - **SizeBuckets** ([]float64) - Optional - The buckets used by Prometheus for the HTTP response size metrics, by default uses a exponential buckets from 100B to 1GB. - **Registry** (prometheus.Registerer) - Optional - The registry that will be used by the recorder to store the metrics, if the default registry is not used then it will use the default one. - **HandlerIDLabel** (string) - Optional - The name that will be set to the handler ID label, by default is `handler`. - **StatusCodeLabel** (string) - Optional - The name that will be set to the status code label, by default is `code`. - **MethodLabel** (string) - Optional - The name that will be set to the method label, by default is `method`. - **ServiceLabel** (string) - Optional - The name that will be set to the service label, by default is `service`. ``` -------------------------------- ### Reporter interface for data collection Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware Defines the interface for reporting HTTP request and response data to the middleware for measurement. Implement this to integrate with different HTTP frameworks. ```go type Reporter interface { Method() string Context() context.Context URLPath() string StatusCode() int BytesWritten() int64 } ``` -------------------------------- ### httprouter.Handler Function Signature Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/httprouter Returns a httprouter.Handler that measures middleware. ```go func Handler(handlerID string, next httprouter.Handle, m middleware.Middleware) httprouter.Handle ``` -------------------------------- ### Handler function signature Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/std Returns a measuring standard http.Handler. Use this when you need to wrap an existing http.Handler with middleware. ```go func Handler(handlerID string, m middleware.Middleware, h http.Handler) http.Handler ``` -------------------------------- ### Reporter StatusCode Method Mock Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/middleware Provides a mock function for the StatusCode method of the Reporter type. ```go func (_m *Reporter) StatusCode() int ``` -------------------------------- ### Handler Function Signature Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/gorestful Defines the signature for the Handler function, which returns a gorestful measuring middleware. ```go func Handler(handlerID string, m middleware.Middleware) gorestful.FilterFunction ``` -------------------------------- ### HTTPProperties Type Definition Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics Defines properties for global server metrics, including service and handler ID. ```go type HTTPProperties struct { // Service is the service that has served the request. Service string // ID is the id of the request handler. ID string } ``` -------------------------------- ### Reporter BytesWritten Method Mock Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/middleware Provides a mock function for the BytesWritten method of the Reporter type. ```go func (_m *Reporter) BytesWritten() int64 ``` -------------------------------- ### Recorder Interface Definition Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics Interface for recording HTTP request metrics, including duration, response size, and inflight requests. ```go type Recorder interface { // ObserveHTTPRequestDuration measures the duration of an HTTP request. ObserveHTTPRequestDuration(ctx context.Context, props HTTPReqProperties, duration time.Duration) // ObserveHTTPResponseSize measures the size of an HTTP response in bytes. ObserveHTTPResponseSize(ctx context.Context, props HTTPReqProperties, sizeBytes int64) // AddInflightRequests increments and decrements the number of inflight request being // processed. AddInflightRequests(ctx context.Context, props HTTPProperties, quantity int) } ``` -------------------------------- ### Handler Function Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/gin The Handler function returns a Gin compatible middleware that measures HTTP requests. ```APIDOC ## func Handler ### Description Handler returns a Gin measuring middleware. ### Signature ```go func Handler(handlerID string, m middleware.Middleware) gin.HandlerFunc ``` ### Parameters * **handlerID** (string) - Required - An identifier for the handler. * **m** (middleware.Middleware) - Required - The middleware to be used for metrics collection. ``` -------------------------------- ### Prometheus Query: Request Rate by Handler Source: https://pkg.go.dev/github.com/slok/go-http-metrics This Prometheus query calculates the request rate for each handler over a 30-second window using the http_request_duration_seconds_count metric. ```promql sum( rate(http_request_duration_seconds_count[30s]) ) by (handler) ``` -------------------------------- ### Handler Function Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/goji The Handler function creates a Goji compatible middleware. It takes a handler ID and a middleware.Middleware to generate a Goji compatible middleware. ```APIDOC ## func Handler ### Description Handler returns a Goji measuring middleware. ### Signature ```go func Handler(handlerID string, m middleware.Middleware) func(http.Handler) http.Handler ``` ### Parameters * **handlerID** (string) - An identifier for the handler. * **m** (middleware.Middleware) - The middleware to be used. ``` -------------------------------- ### HTTPReqProperties Type Definition Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics Defines properties for client request metrics, including service, handler ID, method, and response code. ```go type HTTPReqProperties struct { // Service is the service that has served the request. Service string // ID is the id of the request handler. ID string // Method is the method of the request. Method string // Code is the response of the request. Code string } ``` -------------------------------- ### Echo Handler Function Signature Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/echo This is the function signature for the Handler function in the echo package. It returns an Echo compatible middleware. ```go func Handler(handlerID string, m middleware.Middleware) echo.MiddlewareFunc ``` -------------------------------- ### Handler Function Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/gorestful The Handler function returns a gorestful compatible middleware that can be used to measure requests. ```APIDOC ## func Handler ### Description Handler returns a gorestful measuring middleware. ### Signature ```go func Handler(handlerID string, m middleware.Middleware) gorestful.FilterFunction ``` ### Parameters #### Path Parameters - **handlerID** (string) - Required - Identifier for the handler. - **m** (middleware.Middleware) - Required - The middleware to be applied. ### Returns - **gorestful.FilterFunction** - A gorestful filter function that applies the middleware. ``` -------------------------------- ### Handler Function Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/echo The Handler function returns an Echo middleware that measures HTTP requests. ```APIDOC ## func Handler ### Description Handler returns a Echo measuring middleware. ### Signature ```go func Handler(handlerID string, m middleware.Middleware) echo.MiddlewareFunc ``` ### Parameters * **handlerID** (string) - An identifier for the handler. * **m** (middleware.Middleware) - The middleware to wrap. ``` -------------------------------- ### Reporter Interface Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware The Reporter interface defines methods for retrieving necessary data from an HTTP handler to be measured by the Middleware. Implementations of this interface are specific to the HTTP framework or library being used. ```APIDOC interface Reporter { Method() string Context() context.Context URLPath() string StatusCode() int BytesWritten() int64 } ``` -------------------------------- ### Gin Middleware Handler Function Signature Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/gin Signature for the Handler function which returns a Gin measuring middleware. It requires a handler ID and a middleware.Middleware. ```go func Handler(handlerID string, m middleware.Middleware) gin.HandlerFunc ``` -------------------------------- ### Handler Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/fasthttp Handler returns a fasthttp measuring middleware. It takes a handler ID, a middleware instance, and the next request handler in the chain, returning a new fasthttp request handler. ```APIDOC ## func Handler ### Description Handler returns a fasthttp measuring middleware. ### Signature ```go func Handler(handlerID string, m middleware.Middleware, next fasthttp.RequestHandler) fasthttp.RequestHandler ``` ### Parameters - **handlerID** (string) - An identifier for the handler. - **m** (middleware.Middleware) - The middleware instance to use for metrics collection. - **next** (fasthttp.RequestHandler) - The next request handler in the chain. ``` -------------------------------- ### Handler Function Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/negroni The Handler function creates a Negroni measuring middleware. It takes a handler ID and a middleware.Middleware as input and returns a negroni.Handler. ```APIDOC ## func Handler ### Description Handler returns a Negroni measuring middleware. ### Signature ```go func Handler(handlerID string, m middleware.Middleware) negroni.Handler ``` ### Parameters - **handlerID** (string) - An identifier for the handler. - **m** (middleware.Middleware) - The middleware to be wrapped. ``` -------------------------------- ### Negroni Middleware Function Signature Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/negroni This is the function signature for creating a Negroni measuring middleware. It takes a handler ID and a middleware.Middleware to return a negroni.Handler. ```go func Handler(handlerID string, m middleware.Middleware) negroni.Handler ``` -------------------------------- ### HTTPProperties Struct Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics HTTPProperties are the metric properties for the global server metrics. ```APIDOC ## Type: HTTPProperties HTTPProperties are the metric properties for the global server metrics. ### Fields - **Service** (string) - The service that has served the request. - **ID** (string) - The id of the request handler. ``` -------------------------------- ### Prometheus Query: Percentile 90 of Each Handler Source: https://pkg.go.dev/github.com/slok/go-http-metrics This Prometheus query calculates the 90th percentile of request durations for each handler over a 10-minute window, aggregating histogram buckets by handler and le (le is the upper bound of the bucket). ```promql histogram_quantile(0.9, sum( rate(http_request_duration_seconds_bucket[10m]) ) by (handler, le) ) ``` -------------------------------- ### func Handler Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/httprouter Handler returns a httprouter.Handler measuring middleware. ```APIDOC ## func Handler ### Description Handler returns a httprouter.Handler measuring middleware. ### Signature ```go func Handler(handlerID string, next httprouter.Handle, m middleware.Middleware) httprouter.Handle ``` ### Parameters #### Path Parameters - **handlerID** (string) - Required - Identifier for the handler. - **next** (httprouter.Handle) - Required - The next httprouter handle in the chain. - **m** (middleware.Middleware) - Required - The middleware to apply. ``` -------------------------------- ### Fasthttp Handler Function Signature Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/fasthttp This is the function signature for the Handler which returns a fasthttp measuring middleware. It requires a handler ID, a middleware instance, and the next request handler. ```go func Handler(handlerID string, m middleware.Middleware, next fasthttp.RequestHandler) fasthttp.RequestHandler ``` -------------------------------- ### HandlerProvider Function Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/std The HandlerProvider function returns a handler provider, a common pattern in web frameworks for creating middleware. ```APIDOC ## HandlerProvider Function ### Description Returns a handler provider, which is a defacto standard in some frameworks (e.g: Gorilla, Chi...). This kind of provider is useful for creating middleware in a framework-agnostic way. ### Signature ```go func HandlerProvider(handlerID string, m middleware.Middleware) func(http.Handler) http.Handler ``` ### Parameters * **handlerID** (string) - Identifier for the handler. * **m** (middleware.Middleware) - The middleware to apply. ### Returns * func(http.Handler) http.Handler - A function that takes an http.Handler and returns a new http.Handler with the middleware applied. ``` -------------------------------- ### Recorder Interface Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics The Recorder interface defines the methods for recording and measuring HTTP metrics. It is designed to be used with HTTP middlewares. ```APIDOC ## Interface: Recorder Recorder knows how to record and measure the metrics. This Interface has the required methods to be used with the HTTP middlewares. ### Methods - **ObserveHTTPRequestDuration**(ctx context.Context, props HTTPReqProperties, duration time.Duration) Measures the duration of an HTTP request. - **ObserveHTTPResponseSize**(ctx context.Context, props HTTPReqProperties, sizeBytes int64) Measures the size of an HTTP response in bytes. - **AddInflightRequests**(ctx context.Context, props HTTPProperties, quantity int) Increments and decrements the number of inflight request being processed. ``` -------------------------------- ### Recorder Methods Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/metrics The Recorder type provides methods for recording various HTTP metrics. These methods are typically used in testing scenarios with mock implementations. ```APIDOC ## func (*Recorder) AddInflightRequests ### Description Provides a mock function to add inflight requests. ### Signature func (_m *Recorder) AddInflightRequests(ctx context.Context, props metrics.HTTPProperties, quantity int) ### Parameters - **ctx** (context.Context) - The context for the request. - **props** (metrics.HTTPProperties) - Properties of the HTTP request. - **quantity** (int) - The number of inflight requests to add. ``` ```APIDOC ## func (*Recorder) ObserveHTTPRequestDuration ### Description Provides a mock function to observe the duration of an HTTP request. ### Signature func (_m *Recorder) ObserveHTTPRequestDuration(ctx context.Context, props metrics.HTTPReqProperties, duration time.Duration) ### Parameters - **ctx** (context.Context) - The context for the request. - **props** (metrics.HTTPReqProperties) - Properties of the HTTP request. - **duration** (time.Duration) - The duration of the HTTP request. ``` ```APIDOC ## func (*Recorder) ObserveHTTPResponseSize ### Description Provides a mock function to observe the size of an HTTP response. ### Signature func (_m *Recorder) ObserveHTTPResponseSize(ctx context.Context, props metrics.HTTPReqProperties, sizeBytes int64) ### Parameters - **ctx** (context.Context) - The context for the request. - **props** (metrics.HTTPReqProperties) - Properties of the HTTP request. - **sizeBytes** (int64) - The size of the HTTP response in bytes. ``` -------------------------------- ### Reporter Struct Definition Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/middleware Defines the Reporter struct, which is an autogenerated mock type for the Reporter interface. ```go type Reporter struct { mock.Mock } ``` -------------------------------- ### Prometheus Query: Percentile 99 of Whole Service Source: https://pkg.go.dev/github.com/slok/go-http-metrics This Prometheus query calculates the 99th percentile of request durations for the entire service over a 5-minute window using histogram buckets. ```promql histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m])) ``` -------------------------------- ### Handler Function Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/std The Handler function returns a measuring standard http.Handler, useful for instrumenting HTTP requests. ```APIDOC ## Handler Function ### Description Returns a measuring standard http.Handler. ### Signature ```go func Handler(handlerID string, m middleware.Middleware, h http.Handler) http.Handler ``` ### Parameters * **handlerID** (string) - Identifier for the handler. * **m** (middleware.Middleware) - The middleware to apply. * **h** (http.Handler) - The base http.Handler to wrap. ``` -------------------------------- ### HTTPReqProperties Struct Source: https://pkg.go.dev/github.com/slok/go-http-metrics/metrics HTTPReqProperties are the metric properties for metrics based on client requests. ```APIDOC ## Type: HTTPReqProperties HTTPReqProperties are the metric properties for the metrics based on client request. ### Fields - **Service** (string) - The service that has served the request. - **ID** (string) - The id of the request handler. - **Method** (string) - The method of the request. - **Code** (string) - The response code of the request. ``` -------------------------------- ### Handler Function Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/iris The Handler function returns an Iris compatible middleware that measures HTTP requests. ```APIDOC ## func Handler ### Description Handler returns a Iris measuring middleware. ### Signature ```go func Handler(handlerID string, m middleware.Middleware) iris.Handler ``` ### Parameters - **handlerID** (string) - Required - An identifier for the handler. - **m** (middleware.Middleware) - Required - The middleware to wrap. ``` -------------------------------- ### Recorder Type Definition Source: https://pkg.go.dev/github.com/slok/go-http-metrics/internal/mocks/metrics Defines the Recorder struct, which is an autogenerated mock type for the Recorder interface. Use this when setting up mock metrics recording in tests. ```go type Recorder struct { mock.Mock } ``` -------------------------------- ### Iris Handler Function Signature Source: https://pkg.go.dev/github.com/slok/go-http-metrics/middleware/iris This is the function signature for the Handler function in the Iris package. It is used to create an Iris compatible middleware. ```go func Handler(handlerID string, m middleware.Middleware) iris.Handler ``` -------------------------------- ### Prometheus Query: Request Error Rate Source: https://pkg.go.dev/github.com/slok/go-http-metrics This Prometheus query calculates the error rate of HTTP requests over a 30-second window, specifically targeting responses with status codes in the 5xx range. ```promql rate(http_request_duration_seconds_count{code=~"5.."}[30s]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.