Compare commits

...

5 Commits

Author SHA1 Message Date
Nico Clack
f0d0e27998
Merge c19d29e9137385cc4c1b19cccd979e6dda609c66 into e3118cc378d263454098924ebbde7e8d1dd2e904 2026-01-25 14:37:43 -05:00
Bo-Yi Wu
c19d29e913
Merge branch 'master' into fix-router-static-fs 2026-01-02 18:21:28 +08:00
Nico Clack
7dbe3741fc
Merge branch 'master' into fix-router-static-fs 2025-11-23 14:01:44 +00:00
Nico Clack
8ef5a66294 Add test for nested JavaScript file 2025-11-23 14:01:27 +00:00
Nico Clack
670895b7b2 Fix router.StaticFS 2025-11-23 00:44:36 +00:00
5 changed files with 48 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,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()

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.");