Use the github.com/prometheus/client_golang library to create metrics and expose them via an HTTP endpoint.
- Install the library with
go get github.com/prometheus/client_golang/prometheus. - Import the package and define your metrics in your main file.
- Register your metrics with
prometheus.DefaultRegisterer. - Serve the metrics at
/metricsusinghttp.Handle.
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
requestsTotal = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
},
)
)
func init() {
prometheus.MustRegister(requestsTotal)
}
func main() {
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
requestsTotal.Inc()
w.Write([]byte("Hello World"))
})
http.ListenAndServe(":8080", nil)
}