Record Prometheus Metrics Using Middleware


Go programs use Prometheus’ client_golang to expose metrics. If you need to expose metrics related to http requests sent by client, such as request count or P99 of time-consuming, you can use req’s middleware to record prometheus metrics for all requests. This article will show you the code example.

Example using Response Middleware

package main

import (

var (
	SendHTTPRequests = prometheus.NewCounterVec(
			Name: "send_http_requests_total",
			Help: "Number of the http requests sent since the server started",
		[]string{"method", "host", "path", "code"},
	SendHTTPRequestsDuration = prometheus.NewHistogramVec(
			Name:    "send_http_requests_duration_seconds",
			Help:    "Duration in seconds to send http requests",
			Buckets: prometheus.DefBuckets,
		[]string{"method", "host", "path", "code"},

var client = req.C().
	OnAfterResponse(func(c *req.Client, resp *req.Response) error {
		req := resp.Request

		code := ""
		if resp.Response != nil {
			code = strconv.Itoa(resp.Response.StatusCode)
			req.Method, req.URL.Host, req.URL.Path, code,

		duration := float64(resp.TotalTime()) / float64(time.Second)
			req.Method, req.URL.Host, req.URL.Path, code,

		return nil

func init() {
	prometheus.MustRegister(SendHTTPRequests, SendHTTPRequestsDuration)