~evanj/cms

ref: 892c0c7ea54f6c330a9c4acf52ccfc1ab091b121 cms/pkg/flushresp/flushresp.go -rw-r--r-- 1.4 KiB
892c0c7eEvan J Feat(pkg/flushresp): Break out wrapped response writer into its own 1 year, 11 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package flushresp

import (
	"bytes"
	"net/http"
)

var _ http.ResponseWriter = &Response{}

// Response is to be used in place of an http.ResponseWriter.
// Example:
//   func main() {
//       http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//           w2 := New(w)
//           w2.Header().Add("Content-Type", "text/plain")
//           w2.WriteHeader(http.StatusOK)
//           w2.Write([]byte("hello world"))
//           w2.Flush()
//       })
//   }
type Response struct {
	w http.ResponseWriter
	h http.Header
	c int
	b bytes.Buffer
}

// New will, given an http.ResponseWriter, create a flushresp.Response, which
// is to be used as an http.ResponseWriter (as flushresp.Response implements
// http.ResponseWriter).
func New(w http.ResponseWriter) *Response {
	return &Response{
		w: w,
		h: http.Header{},
		b: bytes.Buffer{},
	}
}

// Header, see http.ResponseWriter
func (rw *Response) Header() http.Header { return rw.h }

// WriteHeader, see http.ResponseWriter
func (rw *Response) WriteHeader(statusCode int) { rw.c = statusCode }

// Write, see http.ResponseWriter
func (rw *Response) Write(bytes []byte) (int, error) { return rw.b.Write(bytes) }

// Flush will complete the Response writing and write data to the underlying
// http.ResponseWriter supplied via flushresp.New.
func (rw *Response) Flush() (int, error) {
	for key := range rw.h {
		rw.w.Header().Add(key, rw.h.Get(key))
	}
	rw.w.WriteHeader(rw.c)
	return rw.w.Write(rw.b.Bytes())
}