Skip to content

Commit 1d055af

Browse files
nikandforappleboy
andauthored
FileFromFS (gin-gonic#2112)
* Context.FileFromFS added * Context File and FileFromFS examples at README Co-authored-by: Bo-Yi Wu <[email protected]>
1 parent 2ff2b19 commit 1d055af

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1182,6 +1182,24 @@ func main() {
11821182
}
11831183
```
11841184

1185+
### Serving data from file
1186+
1187+
```go
1188+
func main() {
1189+
router := gin.Default()
1190+
1191+
router.GET("/local/file", func(c *gin.Context) {
1192+
c.File("local/file.go")
1193+
})
1194+
1195+
var fs http.FileSystem = // ...
1196+
router.GET("/fs/file", func(c *gin.Context) {
1197+
c.FileFromFS("fs/file.go", fs)
1198+
})
1199+
}
1200+
1201+
```
1202+
11851203
### Serving data from reader
11861204

11871205
```go

context.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -925,6 +925,17 @@ func (c *Context) File(filepath string) {
925925
http.ServeFile(c.Writer, c.Request, filepath)
926926
}
927927

928+
// FileFromFS writes the specified file from http.FileSytem into the body stream in an efficient way.
929+
func (c *Context) FileFromFS(filepath string, fs http.FileSystem) {
930+
defer func(old string) {
931+
c.Request.URL.Path = old
932+
}(c.Request.URL.Path)
933+
934+
c.Request.URL.Path = filepath
935+
936+
http.FileServer(fs).ServeHTTP(c.Writer, c.Request)
937+
}
938+
928939
// FileAttachment writes the specified file into the body stream in an efficient way
929940
// On the client side, the file will typically be downloaded with the given filename
930941
func (c *Context) FileAttachment(filepath, filename string) {

context_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -992,6 +992,19 @@ func TestContextRenderFile(t *testing.T) {
992992
assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
993993
}
994994

995+
func TestContextRenderFileFromFS(t *testing.T) {
996+
w := httptest.NewRecorder()
997+
c, _ := CreateTestContext(w)
998+
999+
c.Request, _ = http.NewRequest("GET", "/some/path", nil)
1000+
c.FileFromFS("./gin.go", Dir(".", false))
1001+
1002+
assert.Equal(t, http.StatusOK, w.Code)
1003+
assert.Contains(t, w.Body.String(), "func New() *Engine {")
1004+
assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
1005+
assert.Equal(t, "/some/path", c.Request.URL.Path)
1006+
}
1007+
9951008
func TestContextRenderAttachment(t *testing.T) {
9961009
w := httptest.NewRecorder()
9971010
c, _ := CreateTestContext(w)

0 commit comments

Comments
 (0)