httprouter icon indicating copy to clipboard operation
httprouter copied to clipboard

Add adapter for mixing httprouter.Handler and regular http.HandleFunc

Open wzf1943 opened this issue 6 years ago • 4 comments

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

wzf1943 avatar Apr 19 '19 23:04 wzf1943

Hey, I answered something similar that may help you in an older issue https://github.com/julienschmidt/httprouter/issues/198

falmar avatar May 19 '19 02:05 falmar

Check out github.com/rileyr/middleware

It really helped with chaining middleware with httprouter

mikepc avatar Jun 10 '19 04:06 mikepc

See #198

julienschmidt avatar Oct 03 '19 15:10 julienschmidt

Actually, let's add something to make this easy and intuitive. This should be a rather common use-case.

julienschmidt avatar Oct 03 '19 15:10 julienschmidt