rs / xmux

xmux is a httprouter fork on top of xhandler (net/context aware)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Provide matched route as part of context

atombender opened this issue · comments

It would be useful if the matched route is embedded as a context value. For example, you could build a middleware that computed and logged response time metrics over time on a per-route basis:

func Instrumenter(next xhandler.HandlerC) xhandler.HandlerC {
  return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
    route := RouteFromContext(ctx)  // Hypothetical new function
    now = time.Now()
    next.ServeHTTPC(ctx, w, r)
    elapsed := float64(time.Since(now)) / float64(time.Microsecond)
    logRequest(r, route, elapsed)
  })
}

func logRequest(r *http.Request, route string, elasped float64) {
  // ... update internal table of response time histograms ...
}

...
chain := xhandler.Chain{}
chain.UseC(Instrumentater)
mux.POST("/api/v1/query", chain.HandlerC(xhandler.HandlerFuncC(someHandler)))

I can do a PR if you agree that this is useful.