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.1KB

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