Skip to content

Commit

Permalink
FileFromFS (#2112)
Browse files Browse the repository at this point in the history
* Context.FileFromFS added

* Context File and FileFromFS examples at README

Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
  • Loading branch information
nikandfor and appleboy committed Mar 7, 2020
1 parent 2ff2b19 commit 1d055af
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions context.go
Expand Up @@ -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) {
Expand Down
13 changes: 13 additions & 0 deletions context_test.go
Expand Up @@ -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)
Expand Down

0 comments on commit 1d055af

Please sign in to comment.