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 theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
go
package middleware import ( "net/http"
A maintenance-mode gate in Gin
middleware
atomic-flag
concurrency
Intermediate
8 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.