response.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package entry
  2. import (
  3. "io"
  4. "net/http"
  5. )
  6. // Response is the cached response will be send to the clients
  7. // its fields set at runtime on each of the non-cached executions
  8. // non-cached executions = first execution, and each time after
  9. // cache expiration datetime passed.
  10. type Response struct {
  11. // statusCode for the response cache handler.
  12. statusCode int
  13. // body is the contents will be served by the cache handler.
  14. body []byte
  15. // the total headers of the response, including content type.
  16. headers http.Header
  17. }
  18. // NewResponse returns a new cached Response.
  19. func NewResponse(statusCode int, headers http.Header, body []byte) *Response {
  20. r := new(Response)
  21. r.SetStatusCode(statusCode)
  22. r.SetHeaders(headers)
  23. r.SetBody(body)
  24. return r
  25. }
  26. // SetStatusCode sets a valid status code.
  27. func (r *Response) SetStatusCode(statusCode int) {
  28. if statusCode <= 0 {
  29. statusCode = http.StatusOK
  30. }
  31. r.statusCode = statusCode
  32. }
  33. // StatusCode returns a valid status code.
  34. func (r *Response) StatusCode() int {
  35. return r.statusCode
  36. }
  37. // ContentType returns a valid content type
  38. // func (r *Response) ContentType() string {
  39. // if r.headers == "" {
  40. // r.contentType = "text/html; charset=utf-8"
  41. // }
  42. // return r.contentType
  43. // }
  44. // SetHeaders sets a clone of headers of the cached response.
  45. func (r *Response) SetHeaders(h http.Header) {
  46. r.headers = h.Clone()
  47. }
  48. // Headers returns the total headers of the cached response.
  49. func (r *Response) Headers() http.Header {
  50. return r.headers
  51. }
  52. // SetBody consumes "b" and sets the body of the cached response.
  53. func (r *Response) SetBody(body []byte) {
  54. r.body = make([]byte, len(body))
  55. copy(r.body, body)
  56. }
  57. // Body returns contents will be served by the cache handler.
  58. func (r *Response) Body() []byte {
  59. return r.body
  60. }
  61. // Read implements the io.Reader interface.
  62. func (r *Response) Read(b []byte) (int, error) {
  63. if len(r.body) == 0 {
  64. return 0, io.EOF
  65. }
  66. n := copy(b, r.body)
  67. r.body = r.body[n:]
  68. return n, nil
  69. }
  70. // Bytes returns a copy of the cached response body.
  71. func (r *Response) Bytes() []byte {
  72. return append([]byte(nil), r.body...)
  73. }