httprouter
httprouter copied to clipboard
Add adapter for mixing httprouter.Handler and regular http.HandleFunc
Hi I met a issue to use this router.
I'm trying to add a prometheus midware into our endpoint implementation. But our endpoint are using 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))
}
What I need is I need pass a httprouter.Handle endpoint fucntion pointer into a midware function and generate a new httprouter.Handle. Then I can use this httprouter.Handle to register it into the router. When the requests comes it will call that midware first then call the real endpoint.
Below is what I want to do
func InstrumentHandlerFunc(name string, handler httprouter.Handle) httprouter.Handel {
}
router.Get("/hello", InstrumentHandlerFunc("/hello", r.Hello))
Hey, I answered something similar that may help you in an older issue https://github.com/julienschmidt/httprouter/issues/198
Check out github.com/rileyr/middleware
It really helped with chaining middleware with httprouter
See #198
Actually, let's add something to make this easy and intuitive. This should be a rather common use-case.