Merge 5752de9235832e1e62790af24488c87df0e3a235 into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646

This commit is contained in:
Checo 2026-10-10 12:32:39 +08:00 committed by GitHub
commit 0f3234f9b8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 193 additions and 0 deletions

57
htmlfs_glob_test.go Normal file
View File

@ -0,0 +1,57 @@
package gin_test
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"testing/fstest"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// readdirOnlyFS exposes exactly http.FileSystem's documented interfaces.
type readdirOnlyFS struct{ http.FileSystem }
func (f readdirOnlyFS) Open(name string) (http.File, error) {
file, err := f.FileSystem.Open(name)
if err != nil {
return nil, err
}
return struct{ http.File }{file}, nil
}
func TestLoadHTMLFSHTTPFileSystemGlob(t *testing.T) {
old := gin.Mode()
t.Cleanup(func() { gin.SetMode(old) })
for _, mode := range []string{gin.DebugMode, gin.ReleaseMode} {
for _, backend := range []string{"http-only", "http.FS", "http.Dir"} {
for _, pattern := range []string{"templates/page.html", "templates/*.html", "*/page.html"} {
t.Run(mode+"/"+backend+"/"+pattern, func(t *testing.T) {
gin.SetMode(mode)
engine := gin.New()
source := fstest.MapFS{"templates/page.html": &fstest.MapFile{Data: []byte("Hello {{.name}}")}}
var filesystem http.FileSystem = readdirOnlyFS{http.FS(source)}
switch backend {
case "http.FS":
filesystem = http.FS(source)
case "http.Dir":
root := t.TempDir()
require.NoError(t, os.Mkdir(filepath.Join(root, "templates"), 0o700))
require.NoError(t, os.WriteFile(filepath.Join(root, "templates", "page.html"), source["templates/page.html"].Data, 0o600))
filesystem = http.Dir(root)
}
require.NotPanics(t, func() { engine.LoadHTMLFS(filesystem, pattern) })
engine.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "page.html", gin.H{"name": "Gin"}) })
response := httptest.NewRecorder()
require.NotPanics(t, func() { engine.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil)) })
assert.Equal(t, http.StatusOK, response.Code)
assert.Equal(t, "Hello Gin", response.Body.String())
})
}
}
}
}

View File

@ -3,6 +3,8 @@ package fs
import (
"io/fs"
"net/http"
"slices"
"strings"
)
// FileSystem implements an [fs.FS].
@ -19,3 +21,30 @@ func (o FileSystem) Open(name string) (fs.File, error) {
return fs.File(f), nil
}
// ReadDir adapts http.File.Readdir for globbing through io/fs.
func (o FileSystem) ReadDir(name string) ([]fs.DirEntry, error) {
f, err := o.FileSystem.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
var entries []fs.DirEntry
if dir, ok := f.(fs.ReadDirFile); ok {
entries, err = dir.ReadDir(-1)
} else {
var infos []fs.FileInfo
infos, err = f.Readdir(-1)
if infos != nil {
entries = make([]fs.DirEntry, len(infos))
}
for i, info := range infos {
entries[i] = fs.FileInfoToDirEntry(info)
}
}
slices.SortFunc(entries, func(a, b fs.DirEntry) int {
return strings.Compare(a.Name(), b.Name())
})
return entries, err
}

107
internal/fs/readdir_test.go Normal file
View File

@ -0,0 +1,107 @@
package fs
import (
"errors"
"io/fs"
"net/http"
"testing"
"testing/fstest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type readDirFile struct {
http.File
infos []fs.FileInfo
err error
closed bool
}
func (f *readDirFile) Readdir(count int) ([]fs.FileInfo, error) { return f.infos, f.err }
func (f *readDirFile) Close() error { f.closed = true; return nil }
func TestFileSystemReadDir(t *testing.T) {
source := fstest.MapFS{"z.html": &fstest.MapFile{}, "a.html": &fstest.MapFile{}}
z, err := fs.Stat(source, "z.html")
require.NoError(t, err)
a, err := fs.Stat(source, "a.html")
require.NoError(t, err)
directory := &readDirFile{infos: []fs.FileInfo{z, a}}
filesystem := FileSystem{&mockFileSystem{open: func(name string) (http.File, error) {
assert.Equal(t, ".", name)
return directory, nil
}}}
entries, err := fs.ReadDir(filesystem, ".")
require.NoError(t, err)
require.Len(t, entries, 2)
assert.Equal(t, "a.html", entries[0].Name())
assert.Equal(t, "z.html", entries[1].Name())
assert.True(t, directory.closed)
info, err := entries[0].Info()
require.NoError(t, err)
assert.Equal(t, a, info)
}
type modernReadDirFile struct {
readDirFile
entries []fs.DirEntry
}
func (f *modernReadDirFile) ReadDir(count int) ([]fs.DirEntry, error) { return f.entries, f.err }
func (f *modernReadDirFile) Readdir(count int) ([]fs.FileInfo, error) {
panic("ReadDir should be preferred")
}
func TestFileSystemReadDirPartialAndModern(t *testing.T) {
source := fstest.MapFS{"z.html": &fstest.MapFile{}, "a.html": &fstest.MapFile{}}
z, err := fs.Stat(source, "z.html")
require.NoError(t, err)
a, err := fs.Stat(source, "a.html")
require.NoError(t, err)
sentinel := errors.New("partial directory read")
for _, modern := range []bool{false, true} {
directory := &readDirFile{infos: []fs.FileInfo{z, a}, err: sentinel}
var file http.File = directory
if modern {
file = &modernReadDirFile{readDirFile: *directory, entries: []fs.DirEntry{fs.FileInfoToDirEntry(z), fs.FileInfoToDirEntry(a)}}
}
filesystem := FileSystem{&mockFileSystem{open: func(string) (http.File, error) { return file, nil }}}
entries, err := filesystem.ReadDir(".")
require.ErrorIs(t, err, sentinel)
require.Len(t, entries, 2)
assert.Equal(t, "a.html", entries[0].Name())
assert.Equal(t, "z.html", entries[1].Name())
if modern {
assert.True(t, file.(*modernReadDirFile).closed)
} else {
assert.True(t, directory.closed)
}
}
}
func TestFileSystemReadDirErrors(t *testing.T) {
sentinel := errors.New("directory read failed")
t.Run("open", func(t *testing.T) {
filesystem := FileSystem{&mockFileSystem{open: func(string) (http.File, error) { return nil, sentinel }}}
entries, err := filesystem.ReadDir(".")
require.ErrorIs(t, err, sentinel)
assert.Nil(t, entries)
})
t.Run("read", func(t *testing.T) {
directory := &readDirFile{err: sentinel}
filesystem := FileSystem{&mockFileSystem{open: func(string) (http.File, error) { return directory, nil }}}
entries, err := filesystem.ReadDir(".")
require.ErrorIs(t, err, sentinel)
assert.Nil(t, entries)
assert.True(t, directory.closed)
})
t.Run("empty", func(t *testing.T) {
directory := &readDirFile{}
filesystem := FileSystem{&mockFileSystem{open: func(string) (http.File, error) { return directory, nil }}}
entries, err := filesystem.ReadDir(".")
require.NoError(t, err)
assert.Empty(t, entries)
assert.True(t, directory.closed)
})
}