gin-gonic / gin
1
// Copyright 2018 Gin Core Team.  All rights reserved.
2
// Use of this source code is governed by a MIT style
3
// license that can be found in the LICENSE file.
4

5
package render
6

7
import (
8
	"io"
9
	"net/http"
10
	"strconv"
11
)
12

13
// Reader contains the IO reader and its length, and custom ContentType and other headers.
14
type Reader struct {
15
	ContentType   string
16
	ContentLength int64
17
	Reader        io.Reader
18
	Headers       map[string]string
19
}
20

21
// Render (Reader) writes data with custom ContentType and headers.
22
func (r Reader) Render(w http.ResponseWriter) (err error) {
23 151
	r.WriteContentType(w)
24 151
	if r.ContentLength >= 0 {
25 151
		if r.Headers == nil {
26 151
			r.Headers = map[string]string{}
27
		}
28 151
		r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)
29
	}
30 151
	r.writeHeaders(w, r.Headers)
31 151
	_, err = io.Copy(w, r.Reader)
32 151
	return
33
}
34

35
// WriteContentType (Reader) writes custom ContentType.
36
func (r Reader) WriteContentType(w http.ResponseWriter) {
37 151
	writeContentType(w, []string{r.ContentType})
38
}
39

40
// writeHeaders writes custom Header.
41
func (r Reader) writeHeaders(w http.ResponseWriter, headers map[string]string) {
42 151
	header := w.Header()
43
	for k, v := range headers {
44 151
		if header.Get(k) == "" {
45 151
			header.Set(k, v)
46
		}
47
	}
48
}

Read our documentation on viewing source code .

Loading