Add Lookup func
diff --git a/router.go b/router.go
index c6614b2..f4fff35 100644
--- a/router.go
+++ b/router.go
@@ -254,7 +254,16 @@
}
}
-// Make the router implement the http.Handler interface.
+// Lookup allows the manual lookup of a method + path combo.
+// This is e.g. useful to build a framework around this router.
+func (r *Router) Lookup(method, path string) (Handle, Params, bool) {
+ if root := r.trees[method]; root != nil {
+ return root.getValue(path)
+ }
+ return nil, nil, false
+}
+
+// ServeHTTP makes the router implement the http.Handler interface.
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if r.PanicHandler != nil {
defer r.recv(w, req)
diff --git a/router_test.go b/router_test.go
index f13d598..b87ef0d 100644
--- a/router_test.go
+++ b/router_test.go
@@ -237,6 +237,58 @@
}
}
+func TestRouterLookup(t *testing.T) {
+ routed := false
+ wantHandle := func(_ http.ResponseWriter, _ *http.Request, _ Params) {
+ routed = true
+ }
+ wantParams := Params{Param{"name", "gopher"}}
+
+ router := New()
+
+ // try empty router first
+ handle, _, tsr := router.Lookup("GET", "/nope")
+ if handle != nil {
+ t.Fatalf("Got handle for unregistered pattern: %v", handle)
+ }
+ if tsr {
+ t.Error("Got wrong TSR recommendation!")
+ }
+
+ // insert route and try again
+ router.GET("/user/:name", wantHandle)
+
+ handle, params, tsr := router.Lookup("GET", "/user/gopher")
+ if handle == nil {
+ t.Fatal("Got no handle!")
+ } else {
+ handle(nil, nil, nil)
+ if !routed {
+ t.Fatal("Routing failed!")
+ }
+ }
+
+ if !reflect.DeepEqual(params, wantParams) {
+ t.Fatalf("Wrong parameter values: want %v, got %v", wantParams, params)
+ }
+
+ handle, _, tsr = router.Lookup("GET", "/user/gopher/")
+ if handle != nil {
+ t.Fatalf("Got handle for unregistered pattern: %v", handle)
+ }
+ if !tsr {
+ t.Error("Got no TSR recommendation!")
+ }
+
+ handle, _, tsr = router.Lookup("GET", "/nope")
+ if handle != nil {
+ t.Fatalf("Got handle for unregistered pattern: %v", handle)
+ }
+ if tsr {
+ t.Error("Got wrong TSR recommendation!")
+ }
+}
+
type mockFileSystem struct {
opened bool
}