builder.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package response // import "miniflux.app/http/response"
  5. import (
  6. "compress/flate"
  7. "compress/gzip"
  8. "fmt"
  9. "net/http"
  10. "strings"
  11. "time"
  12. )
  13. const compressionThreshold = 1024
  14. // Builder generates HTTP responses.
  15. type Builder struct {
  16. w http.ResponseWriter
  17. r *http.Request
  18. statusCode int
  19. headers map[string]string
  20. enableCompression bool
  21. body interface{}
  22. }
  23. // WithStatus uses the given status code to build the response.
  24. func (b *Builder) WithStatus(statusCode int) *Builder {
  25. b.statusCode = statusCode
  26. return b
  27. }
  28. // WithHeader adds the given HTTP header to the response.
  29. func (b *Builder) WithHeader(key, value string) *Builder {
  30. b.headers[key] = value
  31. return b
  32. }
  33. // WithBody uses the given body to build the response.
  34. func (b *Builder) WithBody(body interface{}) *Builder {
  35. b.body = body
  36. return b
  37. }
  38. // WithAttachment forces the document to be downloaded by the web browser.
  39. func (b *Builder) WithAttachment(filename string) *Builder {
  40. b.headers["Content-Disposition"] = fmt.Sprintf("attachment; filename=%s", filename)
  41. return b
  42. }
  43. // WithoutCompression disables HTTP compression.
  44. func (b *Builder) WithoutCompression() *Builder {
  45. b.enableCompression = false
  46. return b
  47. }
  48. // WithCaching adds caching headers to the response.
  49. func (b *Builder) WithCaching(etag string, duration time.Duration, callback func(*Builder)) {
  50. b.headers["ETag"] = etag
  51. b.headers["Cache-Control"] = "public"
  52. b.headers["Expires"] = time.Now().Add(duration).Format(time.RFC1123)
  53. if etag == b.r.Header.Get("If-None-Match") {
  54. b.statusCode = http.StatusNotModified
  55. b.body = nil
  56. b.Write()
  57. } else {
  58. callback(b)
  59. }
  60. }
  61. // Write generates the HTTP response.
  62. func (b *Builder) Write() {
  63. if b.body == nil {
  64. b.writeHeaders()
  65. return
  66. }
  67. switch v := b.body.(type) {
  68. case []byte:
  69. b.compress(v)
  70. case string:
  71. b.compress([]byte(v))
  72. case error:
  73. b.compress([]byte(v.Error()))
  74. }
  75. }
  76. func (b *Builder) writeHeaders() {
  77. b.headers["X-XSS-Protection"] = "1; mode=block"
  78. b.headers["X-Content-Type-Options"] = "nosniff"
  79. b.headers["X-Frame-Options"] = "DENY"
  80. b.headers["Content-Security-Policy"] = "default-src 'self'; img-src *; media-src *; frame-src *; child-src *"
  81. for key, value := range b.headers {
  82. b.w.Header().Set(key, value)
  83. }
  84. b.w.WriteHeader(b.statusCode)
  85. }
  86. func (b *Builder) compress(data []byte) {
  87. if b.enableCompression && len(data) > compressionThreshold {
  88. acceptEncoding := b.r.Header.Get("Accept-Encoding")
  89. switch {
  90. case strings.Contains(acceptEncoding, "gzip"):
  91. b.headers["Content-Encoding"] = "gzip"
  92. b.writeHeaders()
  93. gzipWriter := gzip.NewWriter(b.w)
  94. defer gzipWriter.Close()
  95. gzipWriter.Write(data)
  96. return
  97. case strings.Contains(acceptEncoding, "deflate"):
  98. b.headers["Content-Encoding"] = "deflate"
  99. b.writeHeaders()
  100. flateWriter, _ := flate.NewWriter(b.w, -1)
  101. defer flateWriter.Close()
  102. flateWriter.Write(data)
  103. return
  104. }
  105. }
  106. b.writeHeaders()
  107. b.w.Write(data)
  108. }
  109. // New creates a new response builder.
  110. func New(w http.ResponseWriter, r *http.Request) *Builder {
  111. return &Builder{w: w, r: r, statusCode: http.StatusOK, headers: make(map[string]string), enableCompression: true}
  112. }