Here we have a simple HTTP server with endpoint which returns pong as response.

    Compile and run the server

    1. ./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().

    1. func ping(w http.ResponseWriter, req *http.Request) {
    2. pingCounter.Inc()
    3. fmt.Fprintf(w, "pong")
    4. }

    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

    1. package main
    2. import (
    3. "fmt"
    4. "net/http"
    5. "github.com/prometheus/client_golang/prometheus"
    6. "github.com/prometheus/client_golang/prometheus/promhttp"
    7. )
    8. var pingCounter = prometheus.NewCounter(
    9. prometheus.CounterOpts{
    10. Name: "ping_request_count",
    11. Help: "No of request handled by Ping handler",
    12. },
    13. )
    14. func ping(w http.ResponseWriter, req *http.Request) {
    15. pingCounter.Inc()
    16. fmt.Fprintf(w, "pong")
    17. }
    18. func main() {
    19. prometheus.MustRegister(pingCounter)
    20. http.HandleFunc("/ping", ping)
    21. http.Handle("/metrics", promhttp.Handler())
    22. }

    Run the example bash go mod init prom_example go mod tidy go run main.go

    Ping Metric

    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.