From 7ae9e3a262a395832f8c727007d80f4231240b87 Mon Sep 17 00:00:00 2001 From: Abiola Ibrahim Date: Sat, 16 May 2015 16:27:41 +0100 Subject: [PATCH] Rewrite: Added new variables file, dir, fragment. --- middleware/rewrite/rewrite.go | 11 +++++++++++ middleware/rewrite/rewrite_test.go | 8 +++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/middleware/rewrite/rewrite.go b/middleware/rewrite/rewrite.go index 90b6b902..b426b360 100644 --- a/middleware/rewrite/rewrite.go +++ b/middleware/rewrite/rewrite.go @@ -99,6 +99,9 @@ func NewRegexpRule(base, pattern, to string, ext []string) (*RegexpRule, error) var regexpVars []string = []string{ "{path}", "{query}", + "{file}", + "{dir}", + "{frag}", } // Rewrite rewrites the internal location of the current request. @@ -130,6 +133,14 @@ func (r *RegexpRule) Rewrite(req *http.Request) bool { to = strings.Replace(to, v, req.URL.Path[1:], -1) case "{query}": to = strings.Replace(to, v, req.URL.RawQuery, -1) + case "{frag}": + to = strings.Replace(to, v, req.URL.Fragment, -1) + case "{file}": + _, file := path.Split(req.URL.Path) + to = strings.Replace(to, v, file, -1) + case "{dir}": + dir, _ := path.Split(req.URL.Path) + to = path.Clean(strings.Replace(to, v, dir, -1)) } } } diff --git a/middleware/rewrite/rewrite_test.go b/middleware/rewrite/rewrite_test.go index 7dcd6768..684e6b21 100644 --- a/middleware/rewrite/rewrite_test.go +++ b/middleware/rewrite/rewrite_test.go @@ -25,6 +25,9 @@ func TestRewrite(t *testing.T) { []string{"/url/", "a([a-z0-9]*)s([A-Z]{2})", "/to/{path}", ""}, []string{"/ab/", "ab", "/ab?{query}", ".txt|"}, []string{"/ab/", "ab", "/ab?type=html&{query}", ".html|"}, + []string{"/abc/", "ab", "/abc/{file}", ".html|"}, + []string{"/abcd/", "ab", "/a/{dir}/{file}", ".html|"}, + []string{"/abcde/", "ab", "/a#{frag}", ".html|"}, } for _, regexpRule := range regexpRules { @@ -69,7 +72,10 @@ func TestRewrite(t *testing.T) { {"/ab/ab.txt", "/ab"}, {"/ab/ab.txt?name=name", "/ab?name=name"}, {"/ab/ab.html?name=name", "/ab?type=html&name=name"}, - {"/ab/ab.html", "/ab?type=html&"}, + {"/abc/ab.html", "/abc/ab.html"}, + {"/abcd/abcd.html", "/a/abcd/abcd.html"}, + {"/abcde/abcde.html", "/a"}, + {"/abcde/abcde.html#1234", "/a#1234"}, } for i, test := range tests {