Monitoring Go HTTP services with Prometheus and Grafana

Prometheus is an open-source monitoring system that periodically scrapes metrics over HTTP and stores them as time series you can query with PromQL. For a Go service you expose a /metrics endpoint with the official client_golang library, point Prometheus at it, and build dashboards in Grafana.
This post instruments a small HTTP server with three metrics:
- A counter of HTTP requests, by status code and method
- A histogram of request latency
- A gauge of in-flight requests
Prerequisites
Section titled “Prerequisites”- Go 1.26 or later (the current
client_golang, v1.25.0, requires it) - Prometheus
- Grafana
Instrumenting the server
Section titled “Instrumenting the server”Create a module:
mkdir go-prometheus-examplecd go-prometheus-examplego mod init example.com/go-prometheus-exampleCreate main.go:
package main
import ( "log" "net/http" "time"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/client_golang/prometheus/promhttp")
var ( requestsTotal = promauto.NewCounterVec( prometheus.CounterOpts{ Name: "http_requests_total", Help: "Total number of HTTP requests.", }, []string{"handler", "code", "method"}, )
requestDuration = promauto.NewHistogramVec( prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "HTTP request latency in seconds.", Buckets: prometheus.DefBuckets, }, []string{"handler", "code", "method"}, )
inFlight = promauto.NewGauge(prometheus.GaugeOpts{ Name: "http_in_flight_requests", Help: "Number of HTTP requests currently being served.", }))
// instrument wraps a handler so every request updates all three metrics.func instrument(name string, h http.Handler) http.Handler { labels := prometheus.Labels{"handler": name} return promhttp.InstrumentHandlerInFlight(inFlight, promhttp.InstrumentHandlerDuration(requestDuration.MustCurryWith(labels), promhttp.InstrumentHandlerCounter(requestsTotal.MustCurryWith(labels), h), ), )}
func hello(w http.ResponseWriter, r *http.Request) { time.Sleep(100 * time.Millisecond) // simulate some work w.Write([]byte("Hello, Prometheus!\n"))}
func main() { http.Handle("/", instrument("hello", http.HandlerFunc(hello))) http.Handle("/metrics", promhttp.Handler()) log.Fatal(http.ListenAndServe(":8080", nil))}Fetch the dependency and run it:
go mod tidygo run .Hit http://localhost:8080/ a few times, then open http://localhost:8080/metrics. You’ll see your three metrics alongside the go_* and process_* metrics that the default registry exports automatically.
A few notes on the code:
promautoregisters each metric with the default registry, whichpromhttp.Handler()serves.- The
promhttp.InstrumentHandler*middleware fills in thecodeandmethodlabels from the real response. Writing that bookkeeping yourself is easy to get wrong. For example,string(status)on anintproduces a Unicode character, not"200". Usestrconv.Itoaif you ever need to do it by hand. - Those helpers only accept
codeandmethodas free labels. Anything else, likehandlerhere, has to be fixed in advance withMustCurryWith, or they panic. - Label by handler name, not by
r.URL.Path. Raw paths like/users/123create a new time series per ID, and that unbounded cardinality is the most common way to overload Prometheus.
Configuring Prometheus
Section titled “Configuring Prometheus”Create prometheus.yml:
global: scrape_interval: 10s evaluation_interval: 10s
scrape_configs: - job_name: "go-prometheus-example" static_configs: - targets: ["localhost:8080"]Start Prometheus with it:
prometheus --config.file=prometheus.ymlOpen http://localhost:9090/targets to check that the target is UP, then try a few queries in the Prometheus UI:
# Requests per second over the last 5 minutes, by status codesum by (code) (rate(http_requests_total[5m]))
# 95th percentile latencyhistogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))
# Requests being served right nowhttp_in_flight_requestsCounters only go up, so always wrap them in rate() or increase() before graphing. The raw value resets whenever the process restarts.
Visualizing in Grafana
Section titled “Visualizing in Grafana”- Start Grafana and open
http://localhost:3000(the default login isadmin/admin; you’ll be asked to change it). - Go to Connections → Data sources, add Prometheus, and set the URL to
http://localhost:9090. - Create a dashboard and add a Time series panel for each of the queries above. For the latency distribution, a Heatmap panel on
sum by (le) (rate(http_request_duration_seconds_bucket[5m]))shows how the buckets shift over time.
Next steps
Section titled “Next steps”- Pick histogram buckets that match your latency targets.
prometheus.DefBuckets(5 ms to 10 s) is a generic default. - Add alerting rules (for example on error rate or p95 latency) and route them through Alertmanager.
- If you already use OpenTelemetry, its Go SDK can export to Prometheus too, which avoids instrumenting twice.
Further reading
Section titled “Further reading”© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)