Skip to content
This repository has been archived by the owner on Dec 23, 2023. It is now read-only.

Commit

Permalink
Add Context.SendFile to send a file to browser
Browse files Browse the repository at this point in the history
  • Loading branch information
razonyang committed Apr 11, 2020
1 parent 51c76de commit 7b773ba
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ under development
- Add Context.ServeFile: a shortcut of http.ServeFile.
- Add Context.ServeContent: a shortcut of http.ServeContent.
- Add Context.BasicAuth: a shortcut of http.Request.BasicAuth.
- Add Context.SendFile: sends a file to browser.

v1.9.0 April 4, 2020
--------------------
Expand Down
8 changes: 8 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"context"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
Expand Down Expand Up @@ -390,3 +391,10 @@ func (ctx *Context) RouteURL(name string, args ...string) (*url.URL, error) {
func (ctx *Context) BasicAuth() (username, password string, ok bool) {
return ctx.Request.BasicAuth()
}

// SendFile sends a file to browser.
func (ctx *Context) SendFile(filename string, r io.Reader) (err error) {
ctx.Response.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
_, err = io.Copy(ctx.Response, r)
return
}
9 changes: 9 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -685,3 +685,12 @@ func TestContext_BasicAuth(t *testing.T) {
assert.Equal(t, ok1, ok2)
}
}

func TestContext_SendFile(t *testing.T) {
w := httptest.NewRecorder()
ctx := newContext(w, nil)
buf := bytes.NewReader([]byte("bar"))
ctx.SendFile("foo.txt", buf)
assert.Equal(t, "bar", w.Body.String())
assert.Equal(t, w.Header().Get("Content-Disposition"), `attachment; filename="foo.txt"`)
}

0 comments on commit 7b773ba

Please sign in to comment.