2022-05-28 05:42:28 +03:00
|
|
|
// Copyright 2018 Gin Core Team. All rights reserved.
|
2018-08-19 17:52:43 +03:00
|
|
|
// Use of this source code is governed by a MIT style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2018-05-12 06:00:42 +03:00
|
|
|
package render
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
2018-09-15 05:23:32 +03:00
|
|
|
// Reader contains the IO reader and its length, and custom ContentType and other headers.
|
2018-05-12 06:00:42 +03:00
|
|
|
type Reader struct {
|
|
|
|
ContentType string
|
|
|
|
ContentLength int64
|
|
|
|
Reader io.Reader
|
|
|
|
Headers map[string]string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Render (Reader) writes data with custom ContentType and headers.
|
|
|
|
func (r Reader) Render(w http.ResponseWriter) (err error) {
|
|
|
|
r.WriteContentType(w)
|
2019-08-05 04:42:59 +03:00
|
|
|
if r.ContentLength >= 0 {
|
2019-11-25 05:45:53 +03:00
|
|
|
if r.Headers == nil {
|
|
|
|
r.Headers = map[string]string{}
|
|
|
|
}
|
2019-08-05 04:42:59 +03:00
|
|
|
r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)
|
|
|
|
}
|
2018-05-12 06:00:42 +03:00
|
|
|
r.writeHeaders(w, r.Headers)
|
|
|
|
_, err = io.Copy(w, r.Reader)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-09-15 05:23:32 +03:00
|
|
|
// WriteContentType (Reader) writes custom ContentType.
|
2018-05-12 06:00:42 +03:00
|
|
|
func (r Reader) WriteContentType(w http.ResponseWriter) {
|
|
|
|
writeContentType(w, []string{r.ContentType})
|
|
|
|
}
|
|
|
|
|
2018-09-15 05:23:32 +03:00
|
|
|
// writeHeaders writes custom Header.
|
2018-05-12 06:00:42 +03:00
|
|
|
func (r Reader) writeHeaders(w http.ResponseWriter, headers map[string]string) {
|
|
|
|
header := w.Header()
|
|
|
|
for k, v := range headers {
|
2019-02-22 09:20:24 +03:00
|
|
|
if header.Get(k) == "" {
|
|
|
|
header.Set(k, v)
|
2018-05-12 06:00:42 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|