From 9d755cc2167a9ca29bc53b55d442fb3ab444b210 Mon Sep 17 00:00:00 2001 From: Cameron Currie Date: Wed, 6 Feb 2013 15:36:24 -0600 Subject: [PATCH] Inject regex matches into environment Injecting the matches allows handlers to use the matched strings in their logic (e.g. to lookup data by an ID). --- routing.go | 7 ++++--- routing_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/routing.go b/routing.go index 76c9133..a70f278 100644 --- a/routing.go +++ b/routing.go @@ -42,10 +42,11 @@ func Routing(routes map[string]App) Middleware { } return func(env Env, app App) (Status, Headers, Body) { - path := []byte(env.Request().URL.Path) for i, matcher := range matchers { - if matcher.Match(path) { - // Matched a route return it + matches := matcher.FindStringSubmatch(env.Request().URL.Path) + if len(matches) != 0 { + // Matched a route; inject matches and return handler + env["Routing.matches"] = matches return handlers[i](env) } } diff --git a/routing_test.go b/routing_test.go index 8628821..34f4d87 100644 --- a/routing_test.go +++ b/routing_test.go @@ -17,12 +17,21 @@ func routingBTestServer(env Env) (Status, Headers, Body) { return 200, Headers{}, Body("Server B") } +func routingCTestServer(env Env) (Status, Headers, Body) { + if env["Routing.matches"].([]string)[1] == "123" { + return 200, Headers{}, Body("Server C") + } + + return 500, Headers{}, Body("Test Failed") +} + func TestRoutingSuccess(t *testing.T) { // Compile the stack routingStack := new(Stack) routes := make(map[string]App) routes["/a"] = routingATestServer routes["/b"] = routingBTestServer + routes["/c/(.*)"] = routingCTestServer routingStack.Middleware(Routing(routes)) routingApp := routingStack.Compile(routingTestServer) @@ -59,6 +68,23 @@ func TestRoutingSuccess(t *testing.T) { if string(body) != expected { t.Error("Expected body:", string(body), "to equal:", expected) } + + // Request against C + request, err = http.NewRequest("GET", "http://localhost:3000/c/123", nil) + status, _, body = routingApp(Env{"mango.request": &Request{request}}) + + if err != nil { + t.Error(err) + } + + if status != 200 { + t.Error("Expected status to equal 200, got:", status) + } + + expected = "Server C" + if string(body) != expected { + t.Error("Expected body:", string(body), "to equal:", expected) + } } func TestRoutingFailure(t *testing.T) {