response_writer.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // Copyright 2014 Manu Martinez-Almeida. 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. package gin
  5. import (
  6. "bufio"
  7. "io"
  8. "net"
  9. "net/http"
  10. )
  11. const (
  12. noWritten = -1
  13. defaultStatus = 200
  14. )
  15. type (
  16. ResponseWriter interface {
  17. http.ResponseWriter
  18. http.Hijacker
  19. http.Flusher
  20. http.CloseNotifier
  21. Status() int
  22. Size() int
  23. WriteString(string) (int, error)
  24. Written() bool
  25. WriteHeaderNow()
  26. }
  27. responseWriter struct {
  28. http.ResponseWriter
  29. size int
  30. status int
  31. }
  32. )
  33. var _ ResponseWriter = &responseWriter{}
  34. func (w *responseWriter) reset(writer http.ResponseWriter) {
  35. w.ResponseWriter = writer
  36. w.size = noWritten
  37. w.status = defaultStatus
  38. }
  39. func (w *responseWriter) WriteHeader(code int) {
  40. if code > 0 && w.status != code {
  41. if w.Written() {
  42. debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code)
  43. }
  44. w.status = code
  45. }
  46. }
  47. func (w *responseWriter) WriteHeaderNow() {
  48. if !w.Written() {
  49. w.size = 0
  50. w.ResponseWriter.WriteHeader(w.status)
  51. }
  52. }
  53. func (w *responseWriter) Write(data []byte) (n int, err error) {
  54. w.WriteHeaderNow()
  55. n, err = w.ResponseWriter.Write(data)
  56. w.size += n
  57. return
  58. }
  59. func (w *responseWriter) WriteString(s string) (n int, err error) {
  60. w.WriteHeaderNow()
  61. n, err = io.WriteString(w.ResponseWriter, s)
  62. w.size += n
  63. return
  64. }
  65. func (w *responseWriter) Status() int {
  66. return w.status
  67. }
  68. func (w *responseWriter) Size() int {
  69. return w.size
  70. }
  71. func (w *responseWriter) Written() bool {
  72. return w.size != noWritten
  73. }
  74. // Implements the http.Hijacker interface
  75. func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  76. if w.size < 0 {
  77. w.size = 0
  78. }
  79. return w.ResponseWriter.(http.Hijacker).Hijack()
  80. }
  81. // Implements the http.CloseNotify interface
  82. func (w *responseWriter) CloseNotify() <-chan bool {
  83. return w.ResponseWriter.(http.CloseNotifier).CloseNotify()
  84. }
  85. // Implements the http.Flush interface
  86. func (w *responseWriter) Flush() {
  87. w.ResponseWriter.(http.Flusher).Flush()
  88. }