Skip to content

Commit

Permalink
Merge pull request #25 from cwc/regex-matches
Browse files Browse the repository at this point in the history
Inject regex matches into environment
  • Loading branch information
paulbellamy committed Feb 9, 2013
2 parents a2e19a4 + 9d755cc commit 89a3fee
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
7 changes: 4 additions & 3 deletions routing.go
Expand Up @@ -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)
}
}
Expand Down
26 changes: 26 additions & 0 deletions routing_test.go
Expand Up @@ -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)

Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 89a3fee

Please sign in to comment.