From 7baa7dec49410ccc9c9604a306e709a075ddf34b Mon Sep 17 00:00:00 2001 From: nolwn Date: Mon, 7 Sep 2020 15:25:36 -0700 Subject: [PATCH] Setup ServeHTTP on router. --- router.go | 9 +++++++++ router_test.go | 32 +++++++++++--------------------- 2 files changed, 20 insertions(+), 21 deletions(-) diff --git a/router.go b/router.go index 99567df..43a8e49 100644 --- a/router.go +++ b/router.go @@ -154,7 +154,16 @@ func (r *Router) Get(path string, callback http.HandlerFunc) { r.AddRoute(http.MethodGet, path, callback) } +// ServeHTTP is the function that is required by http.Handler. It takes an http.ResponseWriter which +// it uses to write to a response object that will construct a response for the user. It also takes +// an *http.Request which describes the request the user has made. +// +// In the case of this router, all it needs to do is lookup the Handler that has been saved at a given +// path and then call its ServeHTTP. func (r Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { + handler, _ := r.Handler(req) + handler.ServeHTTP(w, req) + return } diff --git a/router_test.go b/router_test.go index ac1062c..010c667 100644 --- a/router_test.go +++ b/router_test.go @@ -45,7 +45,7 @@ func TestAddRouter(t *testing.T) { // checkLookup(router.lookup) } -func TestHandler(t *testing.T) { +func TestServeHTTP(t *testing.T) { router := Router{} path := "/items" expectedBody := "I am /items" @@ -61,17 +61,6 @@ func TestHandler(t *testing.T) { if err != nil { t.Error("Did not find the expected callback handler", err) } - - checkLookup(router.lookup) - -} - -func checkLookup(curr *segment) { - fmt.Printf("%p { path: %s, methods: %v, children: %v}\n", curr, curr.path, curr.methods, curr.children) - - for _, v := range curr.children { - checkLookup(v) - } } func matchAndCheckRoute(r *Router, method string, path string, expectedBody string, expectedCode int) (err error) { @@ -84,15 +73,7 @@ func matchAndCheckRoute(r *Router, method string, path string, expectedBody stri return } - h, pattern := r.Handler(request) - - if pattern != "/items" { - err = fmt.Errorf("The recovered patter does not match: %s", pattern) - - return - } - - h.ServeHTTP(rr, request) + r.ServeHTTP(rr, request) if rr.Code != expectedCode { err = fmt.Errorf("The returned callback did not write 200 to the header. Found %d", rr.Code) @@ -154,3 +135,12 @@ func addAndCheckRoute(r *Router, method string, path string, callback http.Handl return } + +// checkLookup prints out the various saved routes. It's not needed for any test, but is a helpful debugging tool. +func checkLookup(curr *segment) { + fmt.Printf("%p { path: %s, methods: %v, children: %v}\n", curr, curr.path, curr.methods, curr.children) + + for _, v := range curr.children { + checkLookup(v) + } +}