mirror of https://github.com/gin-gonic/gin.git
FileFromFS (#2112)
* Context.FileFromFS added * Context File and FileFromFS examples at README Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
This commit is contained in:
parent
2ff2b19e14
commit
1d055af1bc
18
README.md
18
README.md
|
@ -1182,6 +1182,24 @@ func main() {
|
|||
}
|
||||
```
|
||||
|
||||
### Serving data from file
|
||||
|
||||
```go
|
||||
func main() {
|
||||
router := gin.Default()
|
||||
|
||||
router.GET("/local/file", func(c *gin.Context) {
|
||||
c.File("local/file.go")
|
||||
})
|
||||
|
||||
var fs http.FileSystem = // ...
|
||||
router.GET("/fs/file", func(c *gin.Context) {
|
||||
c.FileFromFS("fs/file.go", fs)
|
||||
})
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Serving data from reader
|
||||
|
||||
```go
|
||||
|
|
11
context.go
11
context.go
|
@ -925,6 +925,17 @@ func (c *Context) File(filepath string) {
|
|||
http.ServeFile(c.Writer, c.Request, filepath)
|
||||
}
|
||||
|
||||
// FileFromFS writes the specified file from http.FileSytem into the body stream in an efficient way.
|
||||
func (c *Context) FileFromFS(filepath string, fs http.FileSystem) {
|
||||
defer func(old string) {
|
||||
c.Request.URL.Path = old
|
||||
}(c.Request.URL.Path)
|
||||
|
||||
c.Request.URL.Path = filepath
|
||||
|
||||
http.FileServer(fs).ServeHTTP(c.Writer, c.Request)
|
||||
}
|
||||
|
||||
// FileAttachment writes the specified file into the body stream in an efficient way
|
||||
// On the client side, the file will typically be downloaded with the given filename
|
||||
func (c *Context) FileAttachment(filepath, filename string) {
|
||||
|
|
|
@ -992,6 +992,19 @@ func TestContextRenderFile(t *testing.T) {
|
|||
assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
func TestContextRenderFileFromFS(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
|
||||
c.Request, _ = http.NewRequest("GET", "/some/path", nil)
|
||||
c.FileFromFS("./gin.go", Dir(".", false))
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Body.String(), "func New() *Engine {")
|
||||
assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
|
||||
assert.Equal(t, "/some/path", c.Request.URL.Path)
|
||||
}
|
||||
|
||||
func TestContextRenderAttachment(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
|
|
Loading…
Reference in New Issue