Fix router.StaticFS

This commit is contained in:
Nico Clack 2025-11-23 00:44:36 +00:00
parent 5fad976b37
commit 670895b7b2
5 changed files with 32 additions and 0 deletions

View File

@ -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 {

View File

@ -5,7 +5,9 @@
package gin
import (
"embed"
"fmt"
"io/fs"
"net/http"
"net/http/httptest"
"os"
@ -646,6 +648,27 @@ 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 TestRouterStaticFSFileNotFound(t *testing.T) {
router := New()

2
testdata/embed/index.html vendored Normal file
View File

@ -0,0 +1,2 @@
<!DOCTYPE html>
Hello embedded world!

View File

@ -0,0 +1,2 @@
<!DOCTYPE html>
This is another simple embedded page.

View File

@ -0,0 +1 @@
console.log("This is a simple embedded JavaScript file.");