diff --git a/routergroup.go b/routergroup.go index b2540ec11e..0fb2c365ec 100644 --- a/routergroup.go +++ b/routergroup.go @@ -223,6 +223,10 @@ func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileS } file := c.Param("filepath") + file = path.Clean("/" + file)[1:] + if file == "" { + file = "." + } // 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 1cae3fce54..b4a1c085ae 100644 --- a/routes_test.go +++ b/routes_test.go @@ -5,7 +5,9 @@ package gin import ( + "embed" "fmt" + "io/fs" "net/http" "net/http/httptest" "os" @@ -646,6 +648,43 @@ func TestRouterStaticFSNotFound(t *testing.T) { assert.Equal(t, "non existent", w.Body.String()) } +//go:embed testdata/embed +var embeddedFolder embed.FS + +const embeddedPath = "testdata/embed" + +func TestRouteStaticFSCleansPath(t *testing.T) { + router := New() + subFS, err := fs.Sub(embeddedFolder, embeddedPath) + require.NoError(t, err) + fs := &OnlyFilesFS{ + FileSystem: http.FS(subFS), + } + router.StaticFS("/", fs) + router.NoRoute(func(c *Context) { + c.String(http.StatusNotFound, "non existent") + }) + + w := PerformRequest(router, http.MethodGet, "/tutorials/making-gin/") + assert.Contains(t, w.Body.String(), "This is another simple embedded page.") +} + +func TestRouteStaticFSNestedJsFile(t *testing.T) { + router := New() + subFS, err := fs.Sub(embeddedFolder, embeddedPath) + require.NoError(t, err) + fs := &OnlyFilesFS{ + FileSystem: http.FS(subFS), + } + router.StaticFS("/", fs) + router.NoRoute(func(c *Context) { + c.String(http.StatusNotFound, "non existent") + }) + + w := PerformRequest(router, http.MethodGet, "/tutorials/making-gin/main.js") + assert.Contains(t, w.Body.String(), "console.log(\"This is a simple embedded JavaScript file.\");") +} + func TestRouterStaticFSFileNotFound(t *testing.T) { router := New() diff --git a/testdata/embed/index.html b/testdata/embed/index.html new file mode 100644 index 0000000000..cacfde8a66 --- /dev/null +++ b/testdata/embed/index.html @@ -0,0 +1,2 @@ + +Hello embedded world! diff --git a/testdata/embed/tutorials/making-gin/index.html b/testdata/embed/tutorials/making-gin/index.html new file mode 100644 index 0000000000..53490fb326 --- /dev/null +++ b/testdata/embed/tutorials/making-gin/index.html @@ -0,0 +1,2 @@ + +This is another simple embedded page. diff --git a/testdata/embed/tutorials/making-gin/main.js b/testdata/embed/tutorials/making-gin/main.js new file mode 100644 index 0000000000..5780c65823 --- /dev/null +++ b/testdata/embed/tutorials/making-gin/main.js @@ -0,0 +1 @@ +console.log("This is a simple embedded JavaScript file.");