...

Source file src/github.com/gin-gonic/gin/render/reader.go

Documentation: github.com/gin-gonic/gin/render

     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  	r.WriteContentType(w)
    24  	if r.ContentLength >= 0 {
    25  		if r.Headers == nil {
    26  			r.Headers = map[string]string{}
    27  		}
    28  		r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)
    29  	}
    30  	r.writeHeaders(w, r.Headers)
    31  	_, err = io.Copy(w, r.Reader)
    32  	return
    33  }
    34  
    35  // WriteContentType (Reader) writes custom ContentType.
    36  func (r Reader) WriteContentType(w http.ResponseWriter) {
    37  	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  	header := w.Header()
    43  	for k, v := range headers {
    44  		if header.Get(k) == "" {
    45  			header.Set(k, v)
    46  		}
    47  	}
    48  }
    49  

View as plain text