Skip to content

Commit 9d755cc

Browse files
committed
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).
1 parent a2e19a4 commit 9d755cc

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

routing.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,11 @@ func Routing(routes map[string]App) Middleware {
4242
}
4343

4444
return func(env Env, app App) (Status, Headers, Body) {
45-
path := []byte(env.Request().URL.Path)
4645
for i, matcher := range matchers {
47-
if matcher.Match(path) {
48-
// Matched a route return it
46+
matches := matcher.FindStringSubmatch(env.Request().URL.Path)
47+
if len(matches) != 0 {
48+
// Matched a route; inject matches and return handler
49+
env["Routing.matches"] = matches
4950
return handlers[i](env)
5051
}
5152
}

routing_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,21 @@ func routingBTestServer(env Env) (Status, Headers, Body) {
1717
return 200, Headers{}, Body("Server B")
1818
}
1919

20+
func routingCTestServer(env Env) (Status, Headers, Body) {
21+
if env["Routing.matches"].([]string)[1] == "123" {
22+
return 200, Headers{}, Body("Server C")
23+
}
24+
25+
return 500, Headers{}, Body("Test Failed")
26+
}
27+
2028
func TestRoutingSuccess(t *testing.T) {
2129
// Compile the stack
2230
routingStack := new(Stack)
2331
routes := make(map[string]App)
2432
routes["/a"] = routingATestServer
2533
routes["/b"] = routingBTestServer
34+
routes["/c/(.*)"] = routingCTestServer
2635
routingStack.Middleware(Routing(routes))
2736
routingApp := routingStack.Compile(routingTestServer)
2837

@@ -59,6 +68,23 @@ func TestRoutingSuccess(t *testing.T) {
5968
if string(body) != expected {
6069
t.Error("Expected body:", string(body), "to equal:", expected)
6170
}
71+
72+
// Request against C
73+
request, err = http.NewRequest("GET", "http://localhost:3000/c/123", nil)
74+
status, _, body = routingApp(Env{"mango.request": &Request{request}})
75+
76+
if err != nil {
77+
t.Error(err)
78+
}
79+
80+
if status != 200 {
81+
t.Error("Expected status to equal 200, got:", status)
82+
}
83+
84+
expected = "Server C"
85+
if string(body) != expected {
86+
t.Error("Expected body:", string(body), "to equal:", expected)
87+
}
6288
}
6389

6490
func TestRoutingFailure(t *testing.T) {

0 commit comments

Comments
 (0)