Skip to content

Commit a908413

Browse files
authored
Merge pull request #1701 from lnenad/master
Adds IgnoreBase parameter to static middleware
2 parents b90e4e8 + 5716616 commit a908413

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-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: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package middleware
33
import (
44
"net/http"
55
"net/http/httptest"
6+
"path/filepath"
67
"testing"
78

89
"github.com/labstack/echo/v4"
@@ -67,4 +68,27 @@ func TestStatic(t *testing.T) {
6768
assert.Equal(http.StatusOK, rec.Code)
6869
assert.Contains(rec.Body.String(), "cert.pem")
6970
}
71+
72+
// IgnoreBase
73+
req = httptest.NewRequest(http.MethodGet, "/_fixture", nil)
74+
rec = httptest.NewRecorder()
75+
config.Root = "../_fixture"
76+
config.IgnoreBase = true
77+
static = StaticWithConfig(config)
78+
c.Echo().Group("_fixture", static)
79+
e.ServeHTTP(rec, req)
80+
81+
assert.Equal(http.StatusOK, rec.Code)
82+
assert.Equal(rec.Header().Get(echo.HeaderContentLength), "122")
83+
84+
req = httptest.NewRequest(http.MethodGet, "/_fixture", nil)
85+
rec = httptest.NewRecorder()
86+
config.Root = "../_fixture"
87+
config.IgnoreBase = false
88+
static = StaticWithConfig(config)
89+
c.Echo().Group("_fixture", static)
90+
e.ServeHTTP(rec, req)
91+
92+
assert.Equal(http.StatusOK, rec.Code)
93+
assert.Contains(rec.Body.String(), filepath.Join("..", "_fixture", "_fixture"))
7094
}

0 commit comments

Comments
 (0)