mirror of
https://github.com/labstack/echo.git
synced 2024-11-24 08:22:21 +02:00
parent
2017e5e541
commit
74f9806b34
@ -58,6 +58,7 @@ func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc {
|
||||
// Initialize
|
||||
for k, v := range config.Rules {
|
||||
k = strings.Replace(k, "*", "(.*)", -1)
|
||||
k = k + "$"
|
||||
config.rulesRegex[regexp.MustCompile(k)] = v
|
||||
}
|
||||
|
||||
@ -74,9 +75,9 @@ func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc {
|
||||
replacer := captureTokens(k, req.URL.Path)
|
||||
if replacer != nil {
|
||||
req.URL.Path = replacer.Replace(v)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
@ -61,3 +62,35 @@ func TestEchoRewritePreMiddleware(t *testing.T) {
|
||||
assert.Equal(t, "/new", req.URL.Path)
|
||||
assert.Equal(t, 200, rec.Code)
|
||||
}
|
||||
|
||||
// Issue #1143
|
||||
func TestRewriteWithConfigPreMiddleware_Issue1143(t *testing.T) {
|
||||
e := echo.New()
|
||||
r := e.Router()
|
||||
|
||||
e.Pre(RewriteWithConfig(RewriteConfig{
|
||||
Rules: map[string]string{
|
||||
"/api/*/mgmt/proj/*/agt": "/api/$1/hosts/$2",
|
||||
"/api/*/mgmt/proj": "/api/$1/eng",
|
||||
},
|
||||
}))
|
||||
|
||||
r.Add(echo.GET, "/api/:version/hosts/:name", func(c echo.Context) error {
|
||||
return c.String(200, "hosts")
|
||||
})
|
||||
r.Add(echo.GET, "/api/:version/eng", func(c echo.Context) error {
|
||||
return c.String(200, "eng")
|
||||
})
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
req := httptest.NewRequest(echo.GET, "/api/v1/mgmt/proj/test/agt", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
e.ServeHTTP(rec, req)
|
||||
assert.Equal(t, "/api/v1/hosts/test", req.URL.Path)
|
||||
assert.Equal(t, 200, rec.Code)
|
||||
|
||||
defer rec.Result().Body.Close()
|
||||
bodyBytes, _ := ioutil.ReadAll(rec.Result().Body)
|
||||
assert.Equal(t, "hosts", string(bodyBytes))
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user