Documentation
¶
Overview ¶
Package ginprom provides a Gin middleware that automatically collects and exposes HTTP request metrics to Prometheus.
It records request counts, latency, request size, and response size, all labelled by HTTP method, status code, and route pattern. Metrics can be exposed through the helper GetMetricHandler and optionally protected with HTTP Basic Authentication via WithBasicAuth.
Basic usage:
r := gin.Default()
r.Use(ginprom.Middleware())
r.GET("/metrics", gin.WrapH(ginprom.GetMetricHandler()))
Index ¶
- Variables
- func GetMetricHandler(opt ...HandlerOption) http.Handler
- func Middleware(options ...Option) gin.HandlerFunc
- func MiddlewareWithMetrics(metrics *MetricsCollection, options ...Option) gin.HandlerFunc
- type HandlerOption
- type MetricsCollection
- type MetricsOption
- func WithCustomBuckets(durationBuckets, sizeBuckets []float64) MetricsOption
- func WithCustomDurationHistogram(histogram *prometheus.HistogramVec) MetricsOption
- func WithCustomRegistry(registry *prometheus.Registry) MetricsOption
- func WithCustomRequestCounter(counter *prometheus.CounterVec) MetricsOption
- func WithCustomRequestSizeHistogram(histogram *prometheus.HistogramVec) MetricsOption
- func WithCustomResponseSizeHistogram(histogram *prometheus.HistogramVec) MetricsOption
- func WithMetricPrefix(prefix string) MetricsOption
- type Option
- func WithAggregateStatusCode(aggregate bool) Option
- func WithFilterPath(filter func(string, string) bool) Option
- func WithFilterRoutes(routes []string) Option
- func WithPathAggregator(aggregator func(string, string, int) string) Option
- func WithRecordDuration(record bool) Option
- func WithRecordRequestSize(record bool) Option
- func WithRecordResponseSize(record bool) Option
- func WithUnmatchedRouteGrouping(enabled bool) Option
- func WithUnmatchedRouteHandling(enabled bool) Option
- func WithUnmatchedRouteMarking(enabled bool) Option
Constants ¶
This section is empty.
Variables ¶
var ( DefaultDurationBuckets = prometheus.ExponentialBuckets(0.001, 2, 15) DefaultSizeBuckets = prometheus.ExponentialBuckets(100, 2, 10) )
Default histogram bucket sets used when no custom buckets are provided.
DefaultDurationBuckets covers request latency from 1 ms up to ~16 s in 15 exponential steps (base 2, start 0.001 s).
DefaultSizeBuckets covers payload sizes from 100 bytes up to ~51 KB in 10 exponential steps (base 2, start 100 bytes).
Functions ¶
func GetMetricHandler ¶
func GetMetricHandler(opt ...HandlerOption) http.Handler
GetMetricHandler returns an http.Handler that serves the default Prometheus metrics page (equivalent to promhttp.Handler). Pass WithBasicAuth to require authentication before metrics are exposed.
func Middleware ¶
func Middleware(options ...Option) gin.HandlerFunc
Middleware returns a Gin handler that records Prometheus metrics for every request using the package-level default metric collectors registered with the global Prometheus registry.
Accept zero or more Option values to tune what is measured:
r.Use(ginprom.Middleware(
ginprom.WithFilterRoutes([]string{"/healthz", "/readyz"}),
ginprom.WithAggregateStatusCode(true),
))
func MiddlewareWithMetrics ¶ added in v1.3.1
func MiddlewareWithMetrics(metrics *MetricsCollection, options ...Option) gin.HandlerFunc
MiddlewareWithMetrics is like Middleware but records metrics into the provided MetricsCollection instead of the package-level default. Use this when you need multiple independent metric namespaces, custom registries, or fine-grained control over the collectors.
Types ¶
type HandlerOption ¶ added in v1.2.0
type HandlerOption func(*handlerConfig)
HandlerOption is a functional option that configures the metrics HTTP handler returned by GetMetricHandler.
func WithBasicAuth ¶ added in v1.2.0
func WithBasicAuth(username, password string) HandlerOption
WithBasicAuth protects the metrics endpoint with HTTP Basic Authentication. Requests that do not supply matching credentials receive a 401 Unauthorized response with a WWW-Authenticate challenge header.
Example:
r.GET("/metrics", gin.WrapH(ginprom.GetMetricHandler(
ginprom.WithBasicAuth("prometheus", "s3cr3t"),
)))
type MetricsCollection ¶ added in v1.3.1
type MetricsCollection struct {
TotalRequests *prometheus.CounterVec
ResponseSize *prometheus.HistogramVec
RequestSize *prometheus.HistogramVec
Duration *prometheus.HistogramVec
Registry *prometheus.Registry // Optional custom registry
}
MetricsCollection groups the four Prometheus collectors used by the middleware: a counter for total requests and three histograms for duration, request size, and response size. An optional custom registry may be set so that metrics are not registered with the default global Prometheus registry.
func NewMetricsCollection ¶ added in v1.3.1
func NewMetricsCollection(opts ...MetricsOption) *MetricsCollection
NewMetricsCollection creates a MetricsCollection and registers all four collectors with Prometheus. Pass MetricsOption functions to customise metric names, buckets, or the target registry.
Example – use a custom registry and a metric name prefix:
reg := prometheus.NewRegistry()
mc := ginprom.NewMetricsCollection(
ginprom.WithCustomRegistry(reg),
ginprom.WithMetricPrefix("myservice"),
)
type MetricsOption ¶ added in v1.3.1
type MetricsOption func(*MetricsCollection)
MetricsOption is a functional option that configures a MetricsCollection. Options are applied in order by NewMetricsCollection.
func WithCustomBuckets ¶ added in v1.3.1
func WithCustomBuckets(durationBuckets, sizeBuckets []float64) MetricsOption
WithCustomBuckets replaces the bucket definitions for all three histogram collectors. durationBuckets configures the request-duration histogram; sizeBuckets configures both the request-size and response-size histograms.
func WithCustomDurationHistogram ¶ added in v1.3.1
func WithCustomDurationHistogram(histogram *prometheus.HistogramVec) MetricsOption
WithCustomDurationHistogram replaces the default request-duration histogram with the provided one. The histogram must carry the same labels as the middleware (status_code, method, path).
func WithCustomRegistry ¶ added in v1.3.1
func WithCustomRegistry(registry *prometheus.Registry) MetricsOption
WithCustomRegistry configures the MetricsCollection to register all collectors with the provided registry instead of the default global one. This is especially useful in tests or when running multiple independent metric namespaces inside the same process.
func WithCustomRequestCounter ¶ added in v1.3.1
func WithCustomRequestCounter(counter *prometheus.CounterVec) MetricsOption
WithCustomRequestCounter replaces the default request-count counter with the provided one. The counter must use the same label set as the middleware (status_code, method, path).
func WithCustomRequestSizeHistogram ¶ added in v1.3.1
func WithCustomRequestSizeHistogram(histogram *prometheus.HistogramVec) MetricsOption
WithCustomRequestSizeHistogram replaces the default request-size histogram with the provided one. The histogram must carry the same labels as the middleware (status_code, method, path).
func WithCustomResponseSizeHistogram ¶ added in v1.3.1
func WithCustomResponseSizeHistogram(histogram *prometheus.HistogramVec) MetricsOption
WithCustomResponseSizeHistogram replaces the default response-size histogram with the provided one. The histogram must carry the same labels as the middleware (status_code, method, path).
func WithMetricPrefix ¶ added in v1.3.1
func WithMetricPrefix(prefix string) MetricsOption
WithMetricPrefix prepends prefix to all four default metric names. For example, passing "myapp" will produce metrics named "myapp_http_requests_total", "myapp_http_request_duration_seconds", etc. This option recreates the four collectors, so it must appear before any individual collector option that should apply to the prefixed names.
type Option ¶
type Option func(*config)
Option is a functional option that configures the Middleware or MiddlewareWithMetrics behaviour. Options are evaluated in order; later options override earlier ones when they affect the same field.
func WithAggregateStatusCode ¶
WithAggregateStatusCode controls status-code label granularity. When enabled, individual codes are bucketed into class labels such as "2xx", "4xx", "5xx", reducing metric cardinality at the cost of less specific alerting. Disabled by default.
func WithFilterPath ¶
WithFilterPath installs a custom filter function that decides, for each request, whether metrics should be skipped. The function receives the Gin route pattern (first argument) and the raw URL path (second argument) and returns true when the request must be excluded from metrics collection.
Example – skip any path that starts with "/internal":
ginprom.WithFilterPath(func(route, path string) bool {
return strings.HasPrefix(path, "/internal")
})
func WithFilterRoutes ¶ added in v1.3.0
WithFilterRoutes registers a list of exact Gin route patterns that should be excluded from metrics collection. The match is performed against the registered pattern (e.g. "/health"), not the raw request URL.
Example:
ginprom.WithFilterRoutes([]string{"/healthz", "/readyz", "/metrics"})
func WithPathAggregator ¶
WithPathAggregator installs a custom function that maps a (route, path, statusCode) triple to the label value used in all four metrics. The default implementation returns route when it is non-empty, "path_4xx" for 4xx unmatched requests, "path_5xx" for 5xx unmatched ones, and "missing_route" otherwise.
Use this option to normalise dynamic segments that Gin does not capture as named parameters, or to further reduce metric cardinality.
func WithRecordDuration ¶
WithRecordDuration enables or disables recording of request durations. When enabled (the default), every request is observed by the http_request_duration_seconds histogram.
func WithRecordRequestSize ¶
WithRecordRequestSize enables or disables recording of HTTP request body sizes. When enabled (the default), every request is observed by the http_request_size_bytes histogram.
func WithRecordResponseSize ¶
WithRecordResponseSize enables or disables recording of HTTP response sizes. When enabled (the default), every response is observed by the http_response_size_bytes histogram.
func WithUnmatchedRouteGrouping ¶ added in v1.3.1
WithUnmatchedRouteGrouping controls whether all unmatched routes are collapsed into a single "/unmatched/*" label value (enabled = true) or recorded individually under "/unmatched<original-path>" (enabled = false). Grouping is the safer default because it prevents metric cardinality explosion caused by random or attacker-supplied URL paths.
func WithUnmatchedRouteHandling ¶ added in v1.3.1
WithUnmatchedRouteHandling controls whether requests that do not match any registered Gin route are still counted in metrics. When enabled (the default), such requests are grouped under an "/unmatched/*" label (see also WithUnmatchedRouteGrouping). Disable this to silently drop all unmatched requests from metrics.
func WithUnmatchedRouteMarking ¶ added in v1.3.1
WithUnmatchedRouteMarking enables or disables the special "/unmatched" prefix added to route patterns that the Gin router did not match. Deprecated in favour of WithUnmatchedRouteHandling, kept for backwards compatibility.