Counters, gauges, histograms, registries, labels, and promhttp handlers.
8 min readGo for SREBuild
client_golang Overview
prometheus/client_golang is the official Go client for Prometheus. It provides metric types, registries, and HTTP handlers. This is the standard library for exposing Prometheus metrics in Go.
Goquick-start.go
25 linesLn 1, Col 1Go
prometheus.MustRegister registers metrics with the default registry. If a metric name is duplicated, MustRegister panics — this catches errors at startup. Use prometheus.Register for non-fatal registration.
Metric Types Deep Dive
Goall-metric-types.go
35 linesLn 1, Col 1Go
Counter: use rate() in PromQL. Gauge: use directly or with delta(). Histogram: use histogram_quantile() and rate(). Summary: quantiles are precomputed — cannot be aggregated across instances. Choose based on aggregation needs.
Registries
Goregistry-management.go
34 linesLn 1, Col 1Go
Custom registries isolate metrics. HandlerFor serves a specific registry. Multiple registries enable multi-tenant metric collection. Unregister removes metrics — useful for dynamic metric lifecycles.
Labels and Cardinality
Golabel-best-practices.go
37 linesLn 1, Col 1Go
Each unique label combination creates a time series. 10 methods x 5 statuses = 50 series. 10 methods x 5 statuses x 1M users = 50M series. Keep cardinality low. Use MustCurryWith for fixed label values.
promhttp Handlers
Gopromhttp-configurations.go
34 linesLn 1, Col 1Go
HandlerFor serves from a specific registry. HTTPErrorOnError returns HTTP 500 on scrape errors. InstrumentedHandler adds metrics about the metrics endpoint. EnableOpenMetrics enables OpenMetrics format.
Testing Metrics
Gotesting-prometheus-metrics.go
58 linesLn 1, Col 1Go
testutil.GatherAndCompare collects metrics and compares against expected output. This catches wrong names, missing labels, and incorrect values. Always test metrics in CI — incorrect metrics are worse than no metrics.
Use testutil for metric testing
testutil.GatherAndCompare is the standard way to test Prometheus metrics. It handles metric gathering, formatting, and comparison. Use it for every custom metric to ensure correctness.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.