response_writer.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. "log"
  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. Written() bool
  24. WriteHeaderNow()
  25. }
  26. responseWriter struct {
  27. http.ResponseWriter
  28. size int
  29. status int
  30. }
  31. )
  32. func (w *responseWriter) reset(writer http.ResponseWriter) {
  33. w.ResponseWriter = writer
  34. w.size = noWritten
  35. w.status = defaultStatus
  36. }
  37. func (w *responseWriter) WriteHeader(code int) {
  38. if code > 0 {
  39. w.status = code
  40. if w.Written() {
  41. log.Println("[GIN] WARNING. Headers were already written!")
  42. }
  43. }
  44. }
  45. func (w *responseWriter) WriteHeaderNow() {
  46. if !w.Written() {
  47. w.size = 0
  48. w.ResponseWriter.WriteHeader(w.status)
  49. }
  50. }
  51. func (w *responseWriter) Write(data []byte) (n int, err error) {
  52. w.WriteHeaderNow()
  53. n, err = w.ResponseWriter.Write(data)
  54. w.size += n
  55. return
  56. }
  57. func (w *responseWriter) Status() int {
  58. return w.status
  59. }
  60. func (w *responseWriter) Size() int {
  61. return w.size
  62. }
  63. func (w *responseWriter) Written() bool {
  64. return w.size != noWritten
  65. }
  66. // Implements the http.Hijacker interface
  67. func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  68. if w.size < 0 {
  69. w.size = 0
  70. }
  71. return w.ResponseWriter.(http.Hijacker).Hijack()
  72. }
  73. // Implements the http.CloseNotify interface
  74. func (w *responseWriter) CloseNotify() <-chan bool {
  75. return w.ResponseWriter.(http.CloseNotifier).CloseNotify()
  76. }
  77. // Implements the http.Flush interface
  78. func (w *responseWriter) Flush() {
  79. w.ResponseWriter.(http.Flusher).Flush()
  80. }