From 9d84969bf6ffa3f92661df85b0f642d5378983e2 Mon Sep 17 00:00:00 2001 From: astaxie Date: Fri, 13 Sep 2013 11:22:14 +0800 Subject: [PATCH] fix #153 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 已经支持了任意定义变量的路由形式,具体的使用请参考: func TestManyRoute(t *testing.T) { r, _ := http.NewRequest("GET", "/beego32-12.html", nil) w := httptest.NewRecorder() handler := NewControllerRegistor() handler.Add("/beego:id([0-9]+)-:page([0-9]+).html", &TestController{}) handler.ServeHTTP(w, r) id := r.URL.Query().Get(":id") page := r.URL.Query().Get(":page") if id != "32" { t.Errorf("url param set to [%s]; want [%s]", id, "32") } if page != "12" { t.Errorf("url param set to [%s]; want [%s]", page, "12") } } --- router.go | 41 +++++++++++++++++++++++++++++++++++++++++ router_test.go | 20 ++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/router.go b/router.go index 387c24ed..f556848b 100644 --- a/router.go +++ b/router.go @@ -94,6 +94,47 @@ func (p *ControllerRegistor) Add(pattern string, c ControllerInterface, mappingM j++ } } + //url like someprefix:id(xxx).html + if strings.Contains(part, ":") && strings.Contains(part, "(") && strings.Contains(part, ")") { + var out []rune + var start bool + var startexp bool + var param []rune + var expt []rune + for _, v := range part { + if start { + if v != '(' { + param = append(param, v) + continue + } + } + if startexp { + if v != ')' { + expt = append(expt, v) + continue + } + } + if v == ':' { + param = make([]rune, 0) + param = append(param, ':') + start = true + } else if v == '(' { + startexp = true + start = false + params[j] = string(param) + j++ + expt = make([]rune, 0) + expt = append(expt, '(') + } else if v == ')' { + startexp = false + expt = append(expt, ')') + out = append(out, expt...) + } else { + out = append(out, v) + } + } + parts[i] = string(out) + } } reflectVal := reflect.ValueOf(c) t := reflect.Indirect(reflectVal).Type() diff --git a/router_test.go b/router_test.go index 10c080cf..a79e5a4f 100644 --- a/router_test.go +++ b/router_test.go @@ -69,6 +69,26 @@ func TestRouteOk(t *testing.T) { } } +func TestManyRoute(t *testing.T) { + + r, _ := http.NewRequest("GET", "/beego32-12.html", nil) + w := httptest.NewRecorder() + + handler := NewControllerRegistor() + handler.Add("/beego:id([0-9]+)-:page([0-9]+).html", &TestController{}) + handler.ServeHTTP(w, r) + + id := r.URL.Query().Get(":id") + page := r.URL.Query().Get(":page") + + if id != "32" { + t.Errorf("url param set to [%s]; want [%s]", id, "32") + } + if page != "12" { + t.Errorf("url param set to [%s]; want [%s]", page, "12") + } +} + func TestNotFound(t *testing.T) { r, _ := http.NewRequest("GET", "/", nil) w := httptest.NewRecorder()