response_writer.go 1.8 KB

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