You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

59 lines
1.3 KiB

  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. package httputil
  7. import (
  8. "bytes"
  9. "net/http"
  10. "strconv"
  11. )
  12. // ResponseBuffer is the current response being composed by its owner.
  13. // It implements http.ResponseWriter and io.WriterTo.
  14. type ResponseBuffer struct {
  15. buf bytes.Buffer
  16. status int
  17. header http.Header
  18. }
  19. // Write implements the http.ResponseWriter interface.
  20. func (rb *ResponseBuffer) Write(p []byte) (int, error) {
  21. return rb.buf.Write(p)
  22. }
  23. // WriteHeader implements the http.ResponseWriter interface.
  24. func (rb *ResponseBuffer) WriteHeader(status int) {
  25. rb.status = status
  26. }
  27. // Header implements the http.ResponseWriter interface.
  28. func (rb *ResponseBuffer) Header() http.Header {
  29. if rb.header == nil {
  30. rb.header = make(http.Header)
  31. }
  32. return rb.header
  33. }
  34. // WriteTo implements the io.WriterTo interface.
  35. func (rb *ResponseBuffer) WriteTo(w http.ResponseWriter) error {
  36. for k, v := range rb.header {
  37. w.Header()[k] = v
  38. }
  39. if rb.buf.Len() > 0 {
  40. w.Header().Set("Content-Length", strconv.Itoa(rb.buf.Len()))
  41. }
  42. if rb.status != 0 {
  43. w.WriteHeader(rb.status)
  44. }
  45. if rb.buf.Len() > 0 {
  46. if _, err := w.Write(rb.buf.Bytes()); err != nil {
  47. return err
  48. }
  49. }
  50. return nil
  51. }