From 8a85626a710056dfd23cb4560e43d16b206655c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Francisco=20Guimar=C3=A3es?= Date: Mon, 22 Aug 2016 18:46:21 -0300 Subject: [PATCH] Inline feature (#637) --- context.go | 15 ++++++++++++++- context_test.go | 13 +++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index d9e66f36..63ac242a 100644 --- a/context.go +++ b/context.go @@ -3,6 +3,7 @@ package echo import ( "encoding/json" "encoding/xml" + "fmt" "io" "mime" "mime/multipart" @@ -140,6 +141,10 @@ type ( // client to save the file. Attachment(io.ReadSeeker, string) error + // Inline sends a response from `io.ReaderSeeker` as inline, opening + // the file in the browser. + Inline(io.ReadSeeker, string) error + // NoContent sends a response with no body and a status code. NoContent(int) error @@ -417,8 +422,16 @@ func (c *echoContext) File(file string) error { } func (c *echoContext) Attachment(r io.ReadSeeker, name string) (err error) { + return c.contentDisposition(r, name, "attachment") +} + +func (c *echoContext) Inline(r io.ReadSeeker, name string) (err error) { + return c.contentDisposition(r, name, "inline") +} + +func (c *echoContext) contentDisposition(r io.ReadSeeker, name, dispositionType string) (err error) { c.response.Header().Set(HeaderContentType, ContentTypeByExtension(name)) - c.response.Header().Set(HeaderContentDisposition, "attachment; filename="+name) + c.response.Header().Set(HeaderContentDisposition, fmt.Sprintf("%s; filename=%s", dispositionType, name)) c.response.WriteHeader(http.StatusOK) _, err = io.Copy(c.response, r) return diff --git a/context_test.go b/context_test.go index 9c23759c..4f47a2ac 100644 --- a/context_test.go +++ b/context_test.go @@ -145,6 +145,19 @@ func TestContext(t *testing.T) { } } + // Inline + rec = test.NewResponseRecorder() + c = e.NewContext(req, rec).(*echoContext) + file, err = os.Open("_fixture/images/walle.png") + if assert.NoError(t, err) { + err = c.Inline(file, "walle.png") + if assert.NoError(t, err) { + assert.Equal(t, http.StatusOK, rec.Status()) + assert.Equal(t, "inline; filename=walle.png", rec.Header().Get(HeaderContentDisposition)) + assert.Equal(t, 219885, rec.Body.Len()) + } + } + // NoContent rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext)