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
Provenance
- Commit
bf78038- Tree
b7a46da- Author
Jean-Christophe Lebreton <jclebreton@gmail.com>- Committer
Bo-Yi Wu <appleboy.tw@gmail.com>- Parent
5636afe
6 files changed+116 added−0 removed
added:render/reader.go+36 added
1+package render2+3+import (4+ "io"5+ "net/http"6+ "strconv"7+)8+9+type Reader struct {10+ ContentType string11+ ContentLength int6412+ Reader io.Reader13+ Headers map[string]string14+}15+16+// Render (Reader) writes data with custom ContentType and headers.17+func (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+}24+25+func (r Reader) WriteContentType(w http.ResponseWriter) {26+ writeContentType(w, []string{r.ContentType})27+}28+29+func (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 lines10 "errors"11 "html/template"12 "net/http"13 "net/http/httptest"14+ "strconv"15+ "strings"16 "testing"17 18 "github.com/stretchr/testify/assert"19 "github.com/ugorji/go/codec"365 unmodified lines385 FuncMap: nil,386 }387 assert.Panics(t, func() { htmlRender.Instance("", nil) })388 }389+390+func TestRenderReader(t *testing.T) {391+ w := httptest.NewRecorder()392+393+ body := "#!PNG some raw data"394+ headers := make(map[string]string)395+ headers["Content-Disposition"] = `attachment; filename="filename.png"`396+397+ err := (Reader{398+ ContentLength: int64(len(body)),399+ ContentType: "image/png",400+ Reader: strings.NewReader(body),401+ Headers: headers,402+ }).Render(w)403+404+ 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 lines24 _ HTMLRender = HTMLDebug{}25 _ HTMLRender = HTMLProduction{}26 _ Render = YAML{}27 _ Render = MsgPack{}28+ _ Render = Reader{}29 )30 31 func writeContentType(w http.ResponseWriter, value []string) {32 header := w.Header()4 unmodified linesmodified:context_test.go+19 added
1469 unmodified lines1470 data, err := c.GetRawData()1471 assert.Nil(t, err)1472 assert.Equal(t, "Fetch binary post data", string(data))1473 }1474+1475+func TestContextRenderDataFromReader(t *testing.T) {1476+ w := httptest.NewRecorder()1477+ c, _ := CreateTestContext(w)1478+1479+ 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"`}1484+1485+ c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1486+1487+ 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 lines740 Data: data,741 })742 }743 744+// DataFromReader writes the specified reader into the body stream and updates the HTTP code.745+func (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+}753+754 // File writes the specified file into the body stream in a efficient way.755 func (c *Context) File(filepath string) {756 http.ServeFile(c.Writer, c.Request, filepath)757 }107 unmodified linesmodified:README.md+27 added
38 unmodified lines39 - [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 lines901 router.Run(":8080")902 }903 ```904 905+### Serving data from reader906+907+```go908+func 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+ }916+917+ reader := response.Body918+ contentLength := response.ContentLength919+ contentType := response.Header.Get("Content-Type")920+921+ extraHeaders := map[string]string{922+ "Content-Disposition": `attachment; filename="gopher.png"`,923+ }924+925+ c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)926+ })927+ router.Run(":8080")928+}929+```930+931 ### HTML rendering932 933 Using LoadHTMLGlob() or LoadHTMLFiles()934 760 unmodified lines