about summary refs log tree commit diff
diff options
context:
space:
mode:
authorFranck Cuny <franck@lumberjaph.net>2013-05-08 21:13:43 -0700
committerFranck Cuny <franck@lumberjaph.net>2013-05-08 21:13:43 -0700
commit7f419b0c2c86eb0b8c711b47392998e33e34bf9d (patch)
treecb464077fad4facbbeb65e2b58e66272b80d38cb
parentRename the package from mooh to router (diff)
downloadpath-router-7f419b0c2c86eb0b8c711b47392998e33e34bf9d.tar.gz
Clean up messy path before matching a request.
Try to clean up messy path (too many slashes for now) in the path before
applying the Match.
-rw-r--r--router.go10
-rw-r--r--router_test.go13
2 files changed, 22 insertions, 1 deletions
diff --git a/router.go b/router.go
index 9b8d453..85573df 100644
--- a/router.go
+++ b/router.go
@@ -5,6 +5,7 @@ import (
 	"fmt"
 	"github.com/franckcuny/web-request"
 	"net/http"
+	"regexp"
 	"strings"
 )
 
@@ -16,6 +17,7 @@ type Router struct {
 }
 
 var defaultHTTPMethods = []string{"GET", "HEAD", "PUT", "POST", "PATCH", "OPTIONS"}
+var reMessyPath = regexp.MustCompile("/{2,}")
 
 // Create a new router.
 func BuildRouter() *Router {
@@ -88,13 +90,19 @@ func (self *Router) AddRoute(route *Route) error {
 	return nil
 }
 
+func (self *Router) canonpath(url string) string {
+	url = reMessyPath.ReplaceAllString(url, "/")
+	return url
+}
+
 // Will try to find a route that match the HTTP Request.
 func (self *Router) Match(request *http.Request) (*Match, error) {
 
 	matches := []*Match{}
 
 	method := request.Method
-	components := strings.Split(request.URL.Path, "/")
+	url := self.canonpath(request.URL.Path)
+	components := strings.Split(url, "/")
 
 	for _, r := range self.routes {
 		match := r.Match(method, components)
diff --git a/router_test.go b/router_test.go
index cb18fba..71fdcaf 100644
--- a/router_test.go
+++ b/router_test.go
@@ -2,6 +2,8 @@ package router
 
 import (
 	"github.com/franckcuny/web-request"
+	"net/http"
+	"net/url"
 	"testing"
 )
 
@@ -142,3 +144,14 @@ func TestAddNotAllowed(t *testing.T) {
 		t.Fatal()
 	}
 }
+
+func TestMessyPath(t *testing.T) {
+	r := BuildRouter()
+	r.AddRoute(&Route{Method: "GET", Path: "/baz", Code: testRoute})
+	req := &http.Request{Method: "GET", URL: &url.URL{Path: "///////baz"}}
+	m, _ := r.Match(req)
+
+	if m == nil {
+		t.Fatal()
+	}
+}