Skip to content
Myr

Serve easily dynamic files with `DataFromReader` context method (#1304)

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

* Add DataFromReader context method * Replace fmt by strconv.FormatInt * Add pull request link to README

authored by Jean-Christophe Lebreton · committed by Bo-Yi Wu · parent 5636afe · Browse files · 6 files+116 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

6 files+116 added−0 removed

  • other:+116 added−0 removed

6 files+116 added−0 removed

added:render/reader.go+36 added
1package render23import (4 "io"5 "net/http"6 "strconv"7)89type Reader struct {10 ContentType string11 ContentLength int6412 Reader io.Reader13 Headers map[string]string14}1516// Render (Reader) writes data with custom ContentType and headers.17func (r Reader) Render(w http.ResponseWriter) (err error) {18 r.WriteContentType(w)19 r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)20 r.writeHeaders(w, r.Headers)21 _, err = io.Copy(w, r.Reader)22 return23}2425func (r Reader) WriteContentType(w http.ResponseWriter) {26 writeContentType(w, []string{r.ContentType})27}2829func (r Reader) writeHeaders(w http.ResponseWriter, headers map[string]string) {30 header := w.Header()31 for k, v := range headers {32 if val := header[k]; len(val) == 0 {33 header[k] = []string{v}34 }35 }36}
modified:render/render_test.go+23 added
9 unmodified lines
10 "errors"11 "html/template"12 "net/http"13 "net/http/httptest"14 "strconv"15 "strings"16 "testing"1718 "github.com/stretchr/testify/assert"19 "github.com/ugorji/go/codec"
365 unmodified lines
385 FuncMap: nil,386 }387 assert.Panics(t, func() { htmlRender.Instance("", nil) })388}389390func TestRenderReader(t *testing.T) {391 w := httptest.NewRecorder()392393 body := "#!PNG some raw data"394 headers := make(map[string]string)395 headers["Content-Disposition"] = `attachment; filename="filename.png"`396397 err := (Reader{398 ContentLength: int64(len(body)),399 ContentType: "image/png",400 Reader: strings.NewReader(body),401 Headers: headers,402 }).Render(w)403404 assert.NoError(t, err)405 assert.Equal(t, body, w.Body.String())406 assert.Equal(t, "image/png", w.HeaderMap.Get("Content-Type"))407 assert.Equal(t, strconv.Itoa(len(body)), w.HeaderMap.Get("Content-Length"))408 assert.Equal(t, headers["Content-Disposition"], w.HeaderMap.Get("Content-Disposition"))409}
modified:render/render.go+1 added
23 unmodified lines
24 _ HTMLRender = HTMLDebug{}25 _ HTMLRender = HTMLProduction{}26 _ Render = YAML{}27 _ Render = MsgPack{}28 _ Render = Reader{}29)3031func writeContentType(w http.ResponseWriter, value []string) {32 header := w.Header()
4 unmodified lines
modified:context_test.go+19 added
1469 unmodified lines
1470 data, err := c.GetRawData()1471 assert.Nil(t, err)1472 assert.Equal(t, "Fetch binary post data", string(data))1473}14741475func TestContextRenderDataFromReader(t *testing.T) {1476 w := httptest.NewRecorder()1477 c, _ := CreateTestContext(w)14781479 body := "#!PNG some raw data"1480 reader := strings.NewReader(body)1481 contentLength := int64(len(body))1482 contentType := "image/png"1483 extraHeaders := map[string]string{"Content-Disposition": `attachment; filename="gopher.png"`}14841485 c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)14861487 assert.Equal(t, http.StatusOK, w.Code)1488 assert.Equal(t, body, w.Body.String())1489 assert.Equal(t, contentType, w.HeaderMap.Get("Content-Type"))1490 assert.Equal(t, fmt.Sprintf("%d", contentLength), w.HeaderMap.Get("Content-Length"))1491 assert.Equal(t, extraHeaders["Content-Disposition"], w.HeaderMap.Get("Content-Disposition"))1492}
modified:context.go+10 added
739 unmodified lines
740 Data: data,741 })742}743744// DataFromReader writes the specified reader into the body stream and updates the HTTP code.745func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) {746 c.Render(code, render.Reader{747 Headers: extraHeaders,748 ContentType: contentType,749 ContentLength: contentLength,750 Reader: reader,751 })752}753754// File writes the specified file into the body stream in a efficient way.755func (c *Context) File(filepath string) {756 http.ServeFile(c.Writer, c.Request, filepath)757}
107 unmodified lines
modified:README.md+27 added
38 unmodified lines
39 - [Multipart/Urlencoded binding](#multiparturlencoded-binding)40 - [XML, JSON and YAML rendering](#xml-json-and-yaml-rendering)41 - [JSONP rendering](#jsonp)42 - [Serving static files](#serving-static-files)43 - [Serving data from reader](#serving-data-from-reader)44 - [HTML rendering](#html-rendering)45 - [Multitemplate](#multitemplate)46 - [Redirects](#redirects)47 - [Custom Middleware](#custom-middleware)
853 unmodified lines
901 router.Run(":8080")902}903```904905### Serving data from reader906907```go908func main() {909 router := gin.Default()910 router.GET("/someDataFromReader", func(c *gin.Context) {911 response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")912 if err != nil || response.StatusCode != http.StatusOK {913 c.Status(http.StatusServiceUnavailable)914 return915 }916917 reader := response.Body918 contentLength := response.ContentLength919 contentType := response.Header.Get("Content-Type")920921 extraHeaders := map[string]string{922 "Content-Disposition": `attachment; filename="gopher.png"`,923 }924925 c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)926 })927 router.Run(":8080")928}929```930931### HTML rendering932933Using LoadHTMLGlob() or LoadHTMLFiles()934
760 unmodified lines