Skip to content

Commit

Permalink
Inject regex matches into environment
Browse files Browse the repository at this point in the history
Injecting the matches allows handlers to use the matched strings in
their logic (e.g. to lookup data by an ID).
  • Loading branch information
cwc committed Feb 6, 2013
1 parent a2e19a4 commit 9d755cc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
7 changes: 4 additions & 3 deletions routing.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 9d755cc

Please sign in to comment.