fix(router): clean StaticFS paths before fs.Open

Preflight Open used the raw filepath param, so trailing-slash
directory URLs failed ValidPath on embed/fs.FS before FileServer
could clean. Match net/http.FileServer with path.Clean("/"+...).

Fixes #4451
This commit is contained in:
RubenPari 2026-08-08 09:58:34 +02:00
parent 34dac209ff
commit 0714c8e198
2 changed files with 21 additions and 1 deletions

View File

@ -222,7 +222,9 @@ func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileS
c.Writer.WriteHeader(http.StatusNotFound)
}
file := c.Param("filepath")
// Normalize like net/http.FileServer so embed/fs.Sub preflight Open
// accepts directory URLs with trailing slashes (#4451).
file := path.Clean("/" + c.Param("filepath"))
// Check if file exists and/or if we have permission to access it
f, err := fs.Open(file)
if err != nil {

View File

@ -11,6 +11,7 @@ import (
"os"
"path/filepath"
"testing"
"testing/fstest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -646,6 +647,23 @@ func TestRouterStaticFSNotFound(t *testing.T) {
assert.Equal(t, "non existent", w.Body.String())
}
func TestRouterStaticFSTrailingSlashEmbed(t *testing.T) {
fsys := fstest.MapFS{
"dir/index.html": &fstest.MapFile{Data: []byte("INDEX")},
"dir/file.txt": &fstest.MapFile{Data: []byte("FILE")},
}
router := New()
router.StaticFS("/static", http.FS(fsys))
w := PerformRequest(router, http.MethodGet, "/static/dir/")
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "INDEX")
w = PerformRequest(router, http.MethodGet, "/static/dir/file.txt")
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "FILE", w.Body.String())
}
func TestRouterStaticFSFileNotFound(t *testing.T) {
router := New()