Skip to content

Commit 3206527

Browse files
committed
Adds IgnoreBase parameter to static middleware
Adds IgnoreBase parameter to static middleware to support the use case of nested route groups
1 parent 502cce2 commit 3206527

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

_fixture/_fixture/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
This directory is used for the static middleware test

middleware/static.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@ type (
3636
// Enable directory browsing.
3737
// Optional. Default value false.
3838
Browse bool `yaml:"browse"`
39+
40+
// Enable ignoring of the base of the URL path.
41+
// Example: when assigning a static middleware to a non root path group,
42+
// the filesystem path is not doubled
43+
// Optional. Default value false.
44+
IgnoreBase bool `yaml:"ignoreBase"`
3945
}
4046
)
4147

@@ -163,6 +169,15 @@ func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc {
163169
}
164170
name := filepath.Join(config.Root, path.Clean("/"+p)) // "/"+ for security
165171

172+
if config.IgnoreBase {
173+
routePath := path.Base(strings.TrimRight(c.Path(), "/*"))
174+
baseURLPath := path.Base(p)
175+
if baseURLPath == routePath {
176+
i := strings.LastIndex(name, routePath)
177+
name = name[:i] + strings.Replace(name[i:], routePath, "", 1)
178+
}
179+
}
180+
166181
fi, err := os.Stat(name)
167182
if err != nil {
168183
if os.IsNotExist(err) {

middleware/static_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,27 @@ func TestStatic(t *testing.T) {
6767
assert.Equal(http.StatusOK, rec.Code)
6868
assert.Contains(rec.Body.String(), "cert.pem")
6969
}
70+
71+
// IgnoreBase
72+
req = httptest.NewRequest(http.MethodGet, "/_fixture", nil)
73+
rec = httptest.NewRecorder()
74+
config.Root = "../_fixture"
75+
config.IgnoreBase = true
76+
static = StaticWithConfig(config)
77+
c.Echo().Group("_fixture", static)
78+
e.ServeHTTP(rec, req)
79+
80+
assert.Equal(http.StatusOK, rec.Code)
81+
assert.Equal(rec.Header().Get(echo.HeaderContentLength), "122")
82+
83+
req = httptest.NewRequest(http.MethodGet, "/_fixture", nil)
84+
rec = httptest.NewRecorder()
85+
config.Root = "../_fixture"
86+
config.IgnoreBase = false
87+
static = StaticWithConfig(config)
88+
c.Echo().Group("_fixture", static)
89+
e.ServeHTTP(rec, req)
90+
91+
assert.Equal(http.StatusOK, rec.Code)
92+
assert.Contains(rec.Body.String(), "..\\_fixture\\_fixture")
7093
}

0 commit comments

Comments
 (0)