Lesson 58 of 60 · Go
Building an Observability Dashboard with Prometheus & Grafana
Duration: 25 minutes
Prometheus Exporter
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
Expose metrics via /metrics endpoint.
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
requestCount = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "http_requests_total", Help: "Total HTTP requests"}, []string{"handler"})
)
func init() { prometheus.MustRegister(requestCount) }
func metricsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestCount.WithLabelValues(r.URL.Path).Inc()
next.ServeHTTP(w, r)
})
}
func main() {
mux := http.NewServeMux()
// … register app handlers …
mux.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", metricsMiddleware(mux))
}
Grafana
- Add Prometheus as a data source (
http://localhost:9090). - Create a dashboard visualizing
http_requests_total.