aboutsummaryrefslogtreecommitdiff
path: root/httputil/respbuf.go
diff options
context:
space:
mode:
Diffstat (limited to 'httputil/respbuf.go')
-rw-r--r--httputil/respbuf.go58
1 files changed, 58 insertions, 0 deletions
diff --git a/httputil/respbuf.go b/httputil/respbuf.go
new file mode 100644
index 0000000..051af21
--- /dev/null
+++ b/httputil/respbuf.go
@@ -0,0 +1,58 @@
1// Copyright 2013 The Go Authors. All rights reserved.
2//
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file or at
5// https://developers.google.com/open-source/licenses/bsd.
6
7package httputil
8
9import (
10 "bytes"
11 "net/http"
12 "strconv"
13)
14
15// ResponseBuffer is the current response being composed by its owner.
16// It implements http.ResponseWriter and io.WriterTo.
17type ResponseBuffer struct {
18 buf bytes.Buffer
19 status int
20 header http.Header
21}
22
23// Write implements the http.ResponseWriter interface.
24func (rb *ResponseBuffer) Write(p []byte) (int, error) {
25 return rb.buf.Write(p)
26}
27
28// WriteHeader implements the http.ResponseWriter interface.
29func (rb *ResponseBuffer) WriteHeader(status int) {
30 rb.status = status
31}
32
33// Header implements the http.ResponseWriter interface.
34func (rb *ResponseBuffer) Header() http.Header {
35 if rb.header == nil {
36 rb.header = make(http.Header)
37 }
38 return rb.header
39}
40
41// WriteTo implements the io.WriterTo interface.
42func (rb *ResponseBuffer) WriteTo(w http.ResponseWriter) error {
43 for k, v := range rb.header {
44 w.Header()[k] = v
45 }
46 if rb.buf.Len() > 0 {
47 w.Header().Set("Content-Length", strconv.Itoa(rb.buf.Len()))
48 }
49 if rb.status != 0 {
50 w.WriteHeader(rb.status)
51 }
52 if rb.buf.Len() > 0 {
53 if _, err := w.Write(rb.buf.Bytes()); err != nil {
54 return err
55 }
56 }
57 return nil
58}