Skip to content

Commit

Permalink
route.go: allow to chain instrumentations (#217)
Browse files Browse the repository at this point in the history
Signed-off-by: Julien Pivotto <roidelapluie@inuits.eu>
  • Loading branch information
roidelapluie authored and brian-brazil committed Jan 13, 2020
1 parent 7680068 commit 629b6ff
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
6 changes: 6 additions & 0 deletions route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ func New() *Router {

// WithInstrumentation returns a router with instrumentation support.
func (r *Router) WithInstrumentation(instrh func(handlerName string, handler http.HandlerFunc) http.HandlerFunc) *Router {
if r.instrh != nil {
newInstrh := instrh
instrh = func(handlerName string, handler http.HandlerFunc) http.HandlerFunc {
return newInstrh(handlerName, r.instrh(handlerName, handler))
}
}
return &Router{rtr: r.rtr, prefix: r.prefix, instrh: instrh}
}

Expand Down
49 changes: 49 additions & 0 deletions route/route_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,52 @@ func TestInstrumentation(t *testing.T) {
}
}
}

func TestInstrumentations(t *testing.T) {
got := make([]string, 0)
cases := []struct {
router *Router
want []string
}{
{
router: New(),
want: []string{},
}, {
router: New().
WithInstrumentation(
func(handlerName string, handler http.HandlerFunc) http.HandlerFunc {
got = append(got, "1"+handlerName)
return handler
}).
WithInstrumentation(
func(handlerName string, handler http.HandlerFunc) http.HandlerFunc {
got = append(got, "2"+handlerName)
return handler
}).
WithInstrumentation(
func(handlerName string, handler http.HandlerFunc) http.HandlerFunc {
got = append(got, "3"+handlerName)
return handler
}),
want: []string{"1/foo", "2/foo", "3/foo"},
},
}

for _, c := range cases {
c.router.Get("/foo", func(w http.ResponseWriter, r *http.Request) {})

r, err := http.NewRequest("GET", "http://localhost:9090/foo", nil)
if err != nil {
t.Fatalf("Error building test request: %s", err)
}
c.router.ServeHTTP(nil, r)
if len(c.want) != len(got) {
t.Fatalf("Unexpected value: want %q, got %q", c.want, got)
}
for i, v := range c.want {
if v != got[i] {
t.Fatalf("Unexpected value: want %q, got %q", c.want, got)
}
}
}
}

0 comments on commit 629b6ff

Please sign in to comment.