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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Middleware that wraps c.Next() can measure the entire downstream handler chain from a single place.
- 2Label cardinality matters: using FullPath() instead of the raw URL keeps metric series bounded per route.
- 3promauto registers metrics at package init, so declaring them as package-level vars keeps setup declarative.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/instrumenting-a-gin-api-with-prometheus-explained-go-4917/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.