0

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))

wzf1943
  • 121
  • 1
  • 9
  • What exactly are you trying to do? It's not clear to me what you mean by "integrate both together" – ifnotak Apr 18 '19 at 04:41
  • Is there any possible that I can create a prometheus midware that return httprouter.Handle as return type and I can pass httprouter.Handle as one of function's parameter. Right now I can only create regular prometheus http.HandleFunc this kind handler function. – wzf1943 Apr 18 '19 at 04:44
  • In the [docs](https://github.com/julienschmidt/httprouter#why-doesnt-this-work-with-httphandler), it states *The router itself implements the http.Handler interface.* so you can use `router.HandleFunc()` and pass `http.HandlerFunc()`. – ifnotak Apr 18 '19 at 08:26

2 Answers2

0

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)
Gerhard
  • 6,850
  • 8
  • 51
  • 81
sooshian
  • 1
  • 1
0

you can use like this.

router.Handler("GET", "/metrics", promhttp.Handler())