httpresponsestatus.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package missinggo
  2. // todo move to httptoo as ResponseRecorder
  3. import (
  4. "bufio"
  5. "net"
  6. "net/http"
  7. "time"
  8. )
  9. // A http.ResponseWriter that tracks the status of the response. The status
  10. // code, and number of bytes written for example.
  11. type StatusResponseWriter struct {
  12. http.ResponseWriter
  13. Code int
  14. BytesWritten int64
  15. Started time.Time
  16. TimeToFirstByte time.Duration // Time to first byte
  17. GotFirstByte bool
  18. WroteHeader Event
  19. Hijacked bool
  20. }
  21. var _ interface {
  22. http.ResponseWriter
  23. http.Hijacker
  24. } = (*StatusResponseWriter)(nil)
  25. func (me *StatusResponseWriter) Write(b []byte) (n int, err error) {
  26. // Exactly how it's done in the standard library. This ensures Code is
  27. // correct.
  28. if !me.WroteHeader.IsSet() {
  29. me.WriteHeader(http.StatusOK)
  30. }
  31. if me.Started.IsZero() {
  32. panic("Started was not initialized")
  33. }
  34. timeBeforeWrite := time.Now()
  35. n, err = me.ResponseWriter.Write(b)
  36. if n > 0 && !me.GotFirstByte {
  37. me.TimeToFirstByte = timeBeforeWrite.Sub(me.Started)
  38. me.GotFirstByte = true
  39. }
  40. me.BytesWritten += int64(n)
  41. return
  42. }
  43. func (me *StatusResponseWriter) WriteHeader(code int) {
  44. me.ResponseWriter.WriteHeader(code)
  45. if !me.WroteHeader.IsSet() {
  46. me.Code = code
  47. me.WroteHeader.Set()
  48. }
  49. }
  50. func (me *StatusResponseWriter) Hijack() (c net.Conn, b *bufio.ReadWriter, err error) {
  51. me.Hijacked = true
  52. c, b, err = me.ResponseWriter.(http.Hijacker).Hijack()
  53. if b.Writer.Buffered() != 0 {
  54. panic("unexpected buffered writes")
  55. }
  56. c = responseConn{c, me}
  57. return
  58. }
  59. type responseConn struct {
  60. net.Conn
  61. s *StatusResponseWriter
  62. }
  63. func (me responseConn) Write(b []byte) (n int, err error) {
  64. n, err = me.Conn.Write(b)
  65. me.s.BytesWritten += int64(n)
  66. return
  67. }