diff --git a/routergroup.go b/routergroup.go index c01b917e..5c26079a 100644 --- a/routergroup.go +++ b/routergroup.go @@ -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 { diff --git a/routes_test.go b/routes_test.go index 1cae3fce..66e8d773 100644 --- a/routes_test.go +++ b/routes_test.go @@ -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()