Skip to content

Commit 6489472

Browse files
committed
router: store params in context only if it has contents
1 parent 21c8d52 commit 6489472

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

router.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -255,9 +255,11 @@ func (r *Router) Handle(method, path string, handle Handle) {
255255
func (r *Router) Handler(method, path string, handler http.Handler) {
256256
r.Handle(method, path,
257257
func(w http.ResponseWriter, req *http.Request, p Params) {
258-
ctx := req.Context()
259-
ctx = context.WithValue(ctx, ParamsKey, p)
260-
req = req.WithContext(ctx)
258+
if len(p) > 0 {
259+
ctx := req.Context()
260+
ctx = context.WithValue(ctx, ParamsKey, p)
261+
req = req.WithContext(ctx)
262+
}
261263
handler.ServeHTTP(w, req)
262264
},
263265
)

router_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,7 @@ func TestRouterLookup(t *testing.T) {
502502

503503
func TestRouterParamsFromContext(t *testing.T) {
504504
routed := false
505+
505506
wantParams := Params{Param{"name", "gopher"}}
506507
handlerFunc := func(_ http.ResponseWriter, req *http.Request) {
507508
// get params from request context
@@ -513,7 +514,20 @@ func TestRouterParamsFromContext(t *testing.T) {
513514

514515
routed = true
515516
}
517+
518+
var nilParams Params
519+
handlerFuncNil := func(_ http.ResponseWriter, req *http.Request) {
520+
// get params from request context
521+
params := ParamsFromContext(req.Context())
522+
523+
if !reflect.DeepEqual(params, nilParams) {
524+
t.Fatalf("Wrong parameter values: want %v, got %v", nilParams, params)
525+
}
526+
527+
routed = true
528+
}
516529
router := New()
530+
router.HandlerFunc(http.MethodGet, "/user", handlerFuncNil)
517531
router.HandlerFunc(http.MethodGet, "/user/:name", handlerFunc)
518532

519533
w := new(mockResponseWriter)
@@ -522,6 +536,13 @@ func TestRouterParamsFromContext(t *testing.T) {
522536
if !routed {
523537
t.Fatal("Routing failed!")
524538
}
539+
540+
routed = false
541+
r, _ = http.NewRequest(http.MethodGet, "/user", nil)
542+
router.ServeHTTP(w, r)
543+
if !routed {
544+
t.Fatal("Routing failed!")
545+
}
525546
}
526547

527548
type mockFileSystem struct {

0 commit comments

Comments
 (0)