reader.go
This file
Path
render/reader.go
43 lines · 1.1 KiB · Go
Last changed by
chore: add some annotations (#1544)田欧before adoptiond510595
History of this fileTake it
chore: add missing copyright and update if/else (#1497)田欧before adoptionb7bb9ba
lines 1–4why, one step back1// Copyright 2018 Gin Core Team. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.4Serve easily dynamic files with `DataFromReader` context method (#1304)Jean-Christophe Lebretonbefore adoptionbf78038
lines 5–12why, one step back5package render67import (8 "io"9 "net/http"10 "strconv"11)12chore: add some annotations (#1544)田欧before adoptiond510595
line 13why, one step back13// Reader contains the IO reader and its length, and custom ContentType and other headers.Serve easily dynamic files with `DataFromReader` context method (#1304)Jean-Christophe Lebretonbefore adoptionbf78038
lines 14–29why, one step back14type Reader struct {15 ContentType string16 ContentLength int6417 Reader io.Reader18 Headers map[string]string19}2021// Render (Reader) writes data with custom ContentType and headers.22func (r Reader) Render(w http.ResponseWriter) (err error) {23 r.WriteContentType(w)24 r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)25 r.writeHeaders(w, r.Headers)26 _, err = io.Copy(w, r.Reader)27 return28}29chore: add some annotations (#1544)田欧before adoptiond510595
line 30why, one step back30// WriteContentType (Reader) writes custom ContentType.Serve easily dynamic files with `DataFromReader` context method (#1304)Jean-Christophe Lebretonbefore adoptionbf78038
lines 31–34why, one step back31func (r Reader) WriteContentType(w http.ResponseWriter) {32 writeContentType(w, []string{r.ContentType})33}34chore: add some annotations (#1544)田欧before adoptiond510595
line 35why, one step back35// writeHeaders writes custom Header.Serve easily dynamic files with `DataFromReader` context method (#1304)Jean-Christophe Lebretonbefore adoptionbf78038
lines 36–43why, one step back36func (r Reader) writeHeaders(w http.ResponseWriter, headers map[string]string) {37 header := w.Header()38 for k, v := range headers {39 if val := header[k]; len(val) == 0 {40 header[k] = []string{v}41 }42 }43}