about summary refs log tree commit diff
diff options
context:
space:
mode:
authorFranck Cuny <franck@lumberjaph.net>2013-04-27 10:20:05 -0700
committerFranck Cuny <franck@lumberjaph.net>2013-04-27 10:20:05 -0700
commit57b12db9e9352f45b9f365a5e96938aacdf25176 (patch)
tree7c8fec8cc37b579bd6b7ec30ef144f8dec81f159
parentAdd exemple for validations in the README. (diff)
downloadpath-router-57b12db9e9352f45b9f365a5e96938aacdf25176.tar.gz
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.
-rw-r--r--route.go11
-rw-r--r--route_test.go39
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()
+	}
+}