From 1d055af1bc15ab3c5965ce0bf99c6f3f44465b56 Mon Sep 17 00:00:00 2001 From: Nikifor Seryakov Date: Sat, 7 Mar 2020 05:23:33 +0300 Subject: [PATCH] FileFromFS (#2112) * Context.FileFromFS added * Context File and FileFromFS examples at README Co-authored-by: Bo-Yi Wu --- README.md | 18 ++++++++++++++++++ context.go | 11 +++++++++++ context_test.go | 13 +++++++++++++ 3 files changed, 42 insertions(+) diff --git a/README.md b/README.md index 4a0ec90..709a15b 100644 --- a/README.md +++ b/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 diff --git a/context.go b/context.go index 1c1b963..1d3e665 100644 --- a/context.go +++ b/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) { diff --git a/context_test.go b/context_test.go index 7f0bca3..78b22c0 100644 --- a/context_test.go +++ b/context_test.go @@ -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)