Ensure a route context is available
This commit is contained in:
parent
3031602cdf
commit
79fa9188c5
3 changed files with 56 additions and 1 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,2 +1,3 @@
|
|||
.idea
|
||||
*.sw?
|
||||
.vscode
|
||||
|
|
|
|||
5
mux.go
5
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
|
||||
|
|
|
|||
51
mux_test.go
51
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 {
|
||||
|
|
|
|||
Loading…
Reference in a new issue