From 79fa9188c5d924a6408a8b8ef4f267acec735a84 Mon Sep 17 00:00:00 2001 From: Peter Kieltyka Date: Sat, 7 May 2016 20:54:51 -0400 Subject: [PATCH] Ensure a route context is available --- .gitignore | 1 + mux.go | 5 ++++- mux_test.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 3d0b6f9..ba22c99 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .idea *.sw? +.vscode diff --git a/mux.go b/mux.go index c4cd106..70a74c0 100644 --- a/mux.go +++ b/mux.go @@ -314,7 +314,10 @@ func (tr treeRouter) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *h // Grab the root context object rctx, _ := ctx.(*Context) if rctx == nil { - rctx = ctx.Value(routeCtxKey).(*Context) + rctx, _ = ctx.Value(routeCtxKey).(*Context) + if rctx == nil { + panic("chi: route context is required.") + } } // The request path diff --git a/mux_test.go b/mux_test.go index 42e53fc..5547416 100644 --- a/mux_test.go +++ b/mux_test.go @@ -15,6 +15,57 @@ import ( "golang.org/x/net/context" ) +func TestMuxServeHTTP(t *testing.T) { + r := NewRouter() + r.Get("/hi", func(ctx context.Context, w http.ResponseWriter, r *http.Request) { + w.Write([]byte("bye")) + }) + r.NotFound(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { + w.WriteHeader(404) + w.Write([]byte("nothing here")) + }) + + // Thanks to https://github.com/mrcpvn for the nice table test code + testcases := []struct { + Method string + Path string + ExpectedStatus int + ExpectedBody string + }{ + { + Method: "GET", + Path: "/hi", + ExpectedStatus: 200, + ExpectedBody: "bye", + }, + { + Method: "GET", + Path: "/hello", + ExpectedStatus: 404, + ExpectedBody: "nothing here", + }, + } + + for _, tc := range testcases { + resp := httptest.NewRecorder() + req, err := http.NewRequest(tc.Method, tc.Path, nil) + if err != nil { + t.Fatalf("%v", err) + } + r.ServeHTTP(resp, req) + b, err := ioutil.ReadAll(resp.Body) + if err != nil { + t.Fatalf("%v", err) + } + if resp.Code != tc.ExpectedStatus { + t.Fatalf("%v != %v", tc.ExpectedStatus, resp.Code) + } + if string(b) != tc.ExpectedBody { + t.Fatalf("%s != %s", tc.ExpectedBody, b) + } + } +} + func TestMux(t *testing.T) { var count uint64 countermw := func(next http.Handler) http.Handler {