Skip to content
Myr

Extend context.File to allow for the content-dispositon attachments via a new method context.Attachment (#1260)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add FileAttachment method to context to allow instant downloads with filenames * Add relevant tests for FileAttachment method

authored by Emmanuel Goh · committed by 田欧 · parent 2dd3193 · Browse files · 2 files+21 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+21 added−0 removed

  • other:+21 added−0 removed

2 files+21 added−0 removed

modified:context_test.go+13 added
977 unmodified lines
978 assert.Contains(t, w.Body.String(), "func New() *Engine {")979 assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))980}981982func TestContextRenderAttachment(t *testing.T) {983 w := httptest.NewRecorder()984 c, _ := CreateTestContext(w)985 newFilename := "new_filename.go"986987 c.Request, _ = http.NewRequest("GET", "/", nil)988 c.FileAttachment("./gin.go", newFilename)989990 assert.Equal(t, 200, w.Code)991 assert.Contains(t, w.Body.String(), "func New() *Engine {")992 assert.Equal(t, fmt.Sprintf("attachment; filename=\"%s\"", newFilename), w.HeaderMap.Get("Content-Disposition"))993}994995// TestContextRenderYAML tests that the response is serialized as YAML996// and Content-Type is set to application/x-yaml997func TestContextRenderYAML(t *testing.T) {998 w := httptest.NewRecorder()
816 unmodified lines
modified:context.go+8 added
4 unmodified lines
5package gin67import (8 "errors"9 "fmt"10 "io"11 "io/ioutil"12 "math"13 "mime/multipart"
866 unmodified lines
880func (c *Context) File(filepath string) {881 http.ServeFile(c.Writer, c.Request, filepath)882}883884// FileAttachment writes the specified file into the body stream in an efficient way885// On the client side, the file will typically be downloaded with the given filename886func (c *Context) FileAttachment(filepath, filename string) {887 c.Writer.Header().Set("content-disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))888 http.ServeFile(c.Writer, c.Request, filepath)889}890891// SSEvent writes a Server-Sent Event into the body stream.892func (c *Context) SSEvent(name string, message interface{}) {893 c.Render(-1, sse.Event{894 Event: name,
133 unmodified lines