Here we have a simple HTTP server with endpoint which returns pong
as response.
Compile and run the server
./server.go
Now open http://localhost:8090/ping
in your browser and you must see pong
.
Now lets add a metric to the server which will instrument the number of requests made to the ping endpoint,the counter metric type is suitable for this as we know the request count doesn’t go down and only increases.
Next lets update the ping Handler to increase the count of the counter using pingCounter.Inc()
.
func ping(w http.ResponseWriter, req *http.Request) {
pingCounter.Inc()
fmt.Fprintf(w, "pong")
}
Then register the counter to the Default Register and expose the metrics.
The prometheus.MustRegister
function registers the pingCounter to the default Register. To expose the metrics the Go Prometheus client library provides the promhttp package. promhttp.Handler()
provides a http.Handler
which exposes the metrics registered in the Default Register.
The sample code depends on the
package main
import (
"fmt"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var pingCounter = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "ping_request_count",
Help: "No of request handled by Ping handler",
},
)
func ping(w http.ResponseWriter, req *http.Request) {
pingCounter.Inc()
fmt.Fprintf(w, "pong")
}
func main() {
prometheus.MustRegister(pingCounter)
http.HandleFunc("/ping", ping)
http.Handle("/metrics", promhttp.Handler())
}
Run the example bash go mod init prom_example go mod tidy go run main.go
Here the pingrequestcount shows that /ping
endpoint was called 3 times.
The DefaultRegister comes with a collector for go runtime metrics and that is why we see other metrics like gothreads, gogoroutines etc.
We have built our first metric exporter. Let’s update our Prometheus config to scrape the metrics from our server.