Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions routergroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
39 changes: 39 additions & 0 deletions routes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
package gin

import (
"embed"
"fmt"
"io/fs"
"net/http"
"net/http/httptest"
"os"
Expand Down Expand Up @@ -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()

Expand Down
2 changes: 2 additions & 0 deletions testdata/embed/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<!DOCTYPE html>
Hello embedded world!
2 changes: 2 additions & 0 deletions testdata/embed/tutorials/making-gin/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<!DOCTYPE html>
This is another simple embedded page.
1 change: 1 addition & 0 deletions testdata/embed/tutorials/making-gin/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("This is a simple embedded JavaScript file.");
Loading