From 57b12db9e9352f45b9f365a5e96938aacdf25176 Mon Sep 17 00:00:00 2001 From: Franck Cuny Date: Sat, 27 Apr 2013 10:20:05 -0700 Subject: Support default value for placeholders in route's path. If a route is created with a Default: &Route{ Path: "/user/:id", Defaults: map[string]string{ "id": "1", }, ... } a request for /user/ will match the route, and set the value for "id" to 1. However, the route /user will not match. --- route.go | 11 +++++++++-- route_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/route.go b/route.go index 9eab0ab..a33a78f 100644 --- a/route.go +++ b/route.go @@ -12,12 +12,13 @@ type Route struct { Method string Path string Code fn + Validations map[string]*regexp.Regexp + Defaults map[string]string components []string requiredNamedComponents map[string]bool optionalNamedComponents map[string]bool length int lengthWithoutOptional int - Validations map[string]*regexp.Regexp } type Match struct { @@ -55,7 +56,13 @@ func (self *Route) Match(method string, components []string) *Match { return nil } - mapping := map[string]string{} + var mapping map[string]string + + if self.Defaults != nil { + mapping = self.Defaults + }else{ + mapping = map[string]string{} + } currentComponentsLength := len(components) diff --git a/route_test.go b/route_test.go index 77a0092..61585f4 100644 --- a/route_test.go +++ b/route_test.go @@ -195,3 +195,42 @@ func TestAmbigiousFail(t *testing.T) { } fmt.Println(err) } + +func TestWithDefaults(t *testing.T) { + router := BuildRouter() + router.AddRoute(&Route{ + Path: "/foo/:bar", + Method: "GET", + Code: testRoute, + Defaults: map[string]string{ + "bar": "baz", + }, + }) + + r := &http.Request{Method: "GET", URL: &url.URL{Path: "/foo/"}} + m, err := router.Match(r) + if m == nil { + t.Fatal() + } + if err != nil { + t.Fatal() + } +} + +func TestWithDefaultNoMatch(t *testing.T) { + router := BuildRouter() + router.AddRoute(&Route{ + Path: "/foo/:bar", + Method: "GET", + Code: testRoute, + Defaults: map[string]string{ + "bar": "baz", + }, + }) + + r := &http.Request{Method: "GET", URL: &url.URL{Path: "/foo"}} + m, _ := router.Match(r) + if m != nil { + t.Fatal() + } +} -- cgit 1.4.1