go 46 lines · 6 steps

Instrumenting a Gin API with Prometheus

A Gin middleware that records request counts and latency as Prometheus metrics, labeled by status, method, and path.

Explained by highlit
1package middleware
2 
3import (
4 "strconv"
5 "time"
6 
7 "github.com/gin-gonic/gin"
8 "github.com/prometheus/client_golang/prometheus"
9 "github.com/prometheus/client_golang/prometheus/promauto"
10)
11 
12var (
13 requestsTotal = promauto.NewCounterVec(
14 prometheus.CounterOpts{
15 Name: "http_requests_total",
16 Help: "Total number of HTTP requests processed, partitioned by status, method and path.",
17 },
18 []string{"status", "method", "path"},
19 )
20 
21 requestDuration = promauto.NewHistogramVec(
22 prometheus.HistogramOpts{
23 Name: "http_request_duration_seconds",
24 Help: "HTTP request latency in seconds.",
25 Buckets: prometheus.DefBuckets,
26 },
27 []string{"method", "path"},
28 )
29)
30 
31func PrometheusMetrics() gin.HandlerFunc {
32 return func(c *gin.Context) {
33 start := time.Now()
34 
35 c.Next()
36 
37 path := c.FullPath()
38 if path == "" {
39 path = "unmatched"
40 }
41 
42 status := strconv.Itoa(c.Writer.Status())
43 requestsTotal.WithLabelValues(status, c.Request.Method, path).Inc()
44 requestDuration.WithLabelValues(c.Request.Method, path).Observe(time.Since(start).Seconds())
45 }
46}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Middleware that wraps c.Next() can measure the entire downstream handler chain from a single place.
  2. 2Label cardinality matters: using FullPath() instead of the raw URL keeps metric series bounded per route.
  3. 3promauto registers metrics at package init, so declaring them as package-level vars keeps setup declarative.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Instrumenting a Gin API with Prometheus — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code