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.

response.go 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package context
  4. import (
  5. "net/http"
  6. )
  7. // ResponseWriter represents a response writer for HTTP
  8. type ResponseWriter interface {
  9. http.ResponseWriter
  10. http.Flusher
  11. Status() int
  12. Before(func(ResponseWriter))
  13. Size() int // used by access logger template
  14. }
  15. var _ ResponseWriter = &Response{}
  16. // Response represents a response
  17. type Response struct {
  18. http.ResponseWriter
  19. written int
  20. status int
  21. befores []func(ResponseWriter)
  22. beforeExecuted bool
  23. }
  24. // Write writes bytes to HTTP endpoint
  25. func (r *Response) Write(bs []byte) (int, error) {
  26. if !r.beforeExecuted {
  27. for _, before := range r.befores {
  28. before(r)
  29. }
  30. r.beforeExecuted = true
  31. }
  32. size, err := r.ResponseWriter.Write(bs)
  33. r.written += size
  34. if err != nil {
  35. return size, err
  36. }
  37. if r.status == 0 {
  38. r.status = http.StatusOK
  39. }
  40. return size, nil
  41. }
  42. func (r *Response) Size() int {
  43. return r.written
  44. }
  45. // WriteHeader write status code
  46. func (r *Response) WriteHeader(statusCode int) {
  47. if !r.beforeExecuted {
  48. for _, before := range r.befores {
  49. before(r)
  50. }
  51. r.beforeExecuted = true
  52. }
  53. if r.status == 0 {
  54. r.status = statusCode
  55. r.ResponseWriter.WriteHeader(statusCode)
  56. }
  57. }
  58. // Flush flushes cached data
  59. func (r *Response) Flush() {
  60. if f, ok := r.ResponseWriter.(http.Flusher); ok {
  61. f.Flush()
  62. }
  63. }
  64. // Status returned status code written
  65. func (r *Response) Status() int {
  66. return r.status
  67. }
  68. // Before allows for a function to be called before the ResponseWriter has been written to. This is
  69. // useful for setting headers or any other operations that must happen before a response has been written.
  70. func (r *Response) Before(f func(ResponseWriter)) {
  71. r.befores = append(r.befores, f)
  72. }
  73. func WrapResponseWriter(resp http.ResponseWriter) *Response {
  74. if v, ok := resp.(*Response); ok {
  75. return v
  76. }
  77. return &Response{
  78. ResponseWriter: resp,
  79. status: 0,
  80. befores: make([]func(ResponseWriter), 0),
  81. }
  82. }