How to pass a httprouter.Handle to a Prometheus http.HandleFunc

1.4k views Asked by At

Cannot pass Prometheus midware into httprouter endpoint definitions.

I'm trying to add a Prometheus midware into our endpoint implementation. But our endpoint are using a third party mux package called httprouter. Then when I tried to add this midware into existing code base, I cannot find a good way to integrate both together.


router := httprouter.New()
router.GET("/hello", r.Hello)

func (r configuration) Hello(w http.ResponseWriter, req *http.Request, ps httprouter.Params)

func InstrumentHandlerFunc(name string, handler http.HandlerFunc) http.HandlerFunc {
    counter := prometheus.NewCounterVec(
        do something...
    )

    duration := prometheus.NewHistogramVec(
        do something...
    )
    return promhttp.InstrumentHandlerDuration(duration,
        promhttp.InstrumentHandlerCounter(counter, handler))
}

My problem is I can not pass my prometheus handle to that httprouter endpoint function as parameter

Below is what I want to do:


func InstrumentHandlerFunc(name string, handler httprouter.Handle) httprouter.Handel {

}

router.Get("/hello", InstrumentHandlerFunc("/hello", r.Hello))

2

There are 2 answers

0
user3136039 On

you can use like this.

router.Handler("GET", "/metrics", promhttp.Handler())
0
sooshian On

If you want to use both of them in the same project, you can achieve the same result with a simple way to listen on different ports

router := httprouter.New()
// register prometheus exporter 
go func() {
    http.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":8080", nil)
}()
http.ListenAndServe(":80", router)