Skip to content

Commit

Permalink
Merge pull request labstack#1701 from lnenad/master
Browse files Browse the repository at this point in the history
Adds IgnoreBase parameter to static middleware
  • Loading branch information
lammel authored Dec 2, 2020
2 parents b90e4e8 + 5716616 commit a908413
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions _fixture/_fixture/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
This directory is used for the static middleware test
15 changes: 15 additions & 0 deletions middleware/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
)

Expand Down Expand Up @@ -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) {
Expand Down
24 changes: 24 additions & 0 deletions middleware/static_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package middleware
import (
"net/http"
"net/http/httptest"
"path/filepath"
"testing"

"github.com/labstack/echo/v4"
Expand Down Expand Up @@ -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"))
}

0 comments on commit a908413

Please sign in to comment.