mirror of
https://github.com/labstack/echo.git
synced 2025-06-04 23:37:45 +02:00
Merge pull request #1701 from lnenad/master
Adds IgnoreBase parameter to static middleware
This commit is contained in:
commit
a908413281
1
_fixture/_fixture/README.md
Normal file
1
_fixture/_fixture/README.md
Normal file
@ -0,0 +1 @@
|
||||
This directory is used for the static middleware test
|
@ -36,6 +36,12 @@ type (
|
||||
// Enable directory browsing.
|
||||
// Optional. Default value false.
|
||||
Browse bool `yaml:"browse"`
|
||||
|
||||
// Enable ignoring of the base of the URL path.
|
||||
// Example: when assigning a static middleware to a non root path group,
|
||||
// the filesystem path is not doubled
|
||||
// Optional. Default value false.
|
||||
IgnoreBase bool `yaml:"ignoreBase"`
|
||||
}
|
||||
)
|
||||
|
||||
@ -163,6 +169,15 @@ func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc {
|
||||
}
|
||||
name := filepath.Join(config.Root, path.Clean("/"+p)) // "/"+ for security
|
||||
|
||||
if config.IgnoreBase {
|
||||
routePath := path.Base(strings.TrimRight(c.Path(), "/*"))
|
||||
baseURLPath := path.Base(p)
|
||||
if baseURLPath == routePath {
|
||||
i := strings.LastIndex(name, routePath)
|
||||
name = name[:i] + strings.Replace(name[i:], routePath, "", 1)
|
||||
}
|
||||
}
|
||||
|
||||
fi, err := os.Stat(name)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
|
@ -3,6 +3,7 @@ package middleware
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
@ -67,4 +68,27 @@ func TestStatic(t *testing.T) {
|
||||
assert.Equal(http.StatusOK, rec.Code)
|
||||
assert.Contains(rec.Body.String(), "cert.pem")
|
||||
}
|
||||
|
||||
// IgnoreBase
|
||||
req = httptest.NewRequest(http.MethodGet, "/_fixture", nil)
|
||||
rec = httptest.NewRecorder()
|
||||
config.Root = "../_fixture"
|
||||
config.IgnoreBase = true
|
||||
static = StaticWithConfig(config)
|
||||
c.Echo().Group("_fixture", static)
|
||||
e.ServeHTTP(rec, req)
|
||||
|
||||
assert.Equal(http.StatusOK, rec.Code)
|
||||
assert.Equal(rec.Header().Get(echo.HeaderContentLength), "122")
|
||||
|
||||
req = httptest.NewRequest(http.MethodGet, "/_fixture", nil)
|
||||
rec = httptest.NewRecorder()
|
||||
config.Root = "../_fixture"
|
||||
config.IgnoreBase = false
|
||||
static = StaticWithConfig(config)
|
||||
c.Echo().Group("_fixture", static)
|
||||
e.ServeHTTP(rec, req)
|
||||
|
||||
assert.Equal(http.StatusOK, rec.Code)
|
||||
assert.Contains(rec.Body.String(), filepath.Join("..", "_fixture", "_fixture"))
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user