Merge 7dbe3741fc111e3cf0daa26c2190d006052321cb into 19b877fa50cbbb9282763099fb177a1e5cc5c850

This commit is contained in:
Nico Clack 2025-12-07 01:40:10 -05:00 committed by GitHub
commit f271fd835b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
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.");