Merge 64b1517faf9b536d0ec755887648c8bdf0f927ef into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646

This commit is contained in:
deepakganesh78 2026-10-12 06:24:51 -04:00 committed by GitHub
commit e2b2c32bef
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 34 additions and 0 deletions

View File

@ -1343,6 +1343,24 @@ func (c *Context) File(filepath string) {
// FileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way.
func (c *Context) FileFromFS(filepath string, fs http.FileSystem) {
file, err := fs.Open(filepath)
if err != nil {
http.NotFound(c.Writer, c.Request)
return
}
defer file.Close()
info, err := file.Stat()
if err != nil {
http.NotFound(c.Writer, c.Request)
return
}
if !info.IsDir() {
http.ServeContent(c.Writer, c.Request, filepath, info.ModTime(), file)
return
}
defer func(old string) {
c.Request.URL.Path = old
}(c.Request.URL.Path)

View File

@ -25,6 +25,7 @@ import (
"strings"
"sync"
"testing"
"testing/fstest"
"time"
"github.com/gin-contrib/sse"
@ -1658,6 +1659,21 @@ func TestContextRenderFileFromFS(t *testing.T) {
assert.Equal(t, "/some/path", c.Request.URL.Path)
}
func TestContextRenderFileFromFSIndexHTML(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)
c.FileFromFS("www/index.html", http.FS(fstest.MapFS{
"www/index.html": {Data: []byte("index")},
}))
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "index", w.Body.String())
assert.Empty(t, w.Header().Get("Location"))
assert.Equal(t, "/", c.Request.URL.Path)
}
func TestContextRenderAttachment(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)