Skip to content
Browse files

Merge pull request #25 from cwc/regex-matches

Inject regex matches into environment
  • Loading branch information...
2 parents a2e19a4 + 9d755cc commit 89a3fee70fffd3ce66d73061b977117983d838bd @paulbellamy committed Feb 9, 2013
Showing with 30 additions and 3 deletions.
  1. +4 −3 routing.go
  2. +26 −0 routing_test.go
View
7 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)
}
}
View
26 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) {

0 comments on commit 89a3fee

Please sign in to comment.
Something went wrong with that request. Please try again.