From 0714c8e1983e50c395bf91b27d526cc9d1d7da56 Mon Sep 17 00:00:00 2001 From: RubenPari Date: Sat, 8 Aug 2026 09:58:34 +0200 Subject: [PATCH] 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 --- routergroup.go | 4 +++- routes_test.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) 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()