builder.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package response // import "miniflux.app/v2/internal/http/response"
  4. import (
  5. "compress/flate"
  6. "compress/gzip"
  7. "io"
  8. "log/slog"
  9. "mime"
  10. "net/http"
  11. "strings"
  12. "time"
  13. "github.com/andybalholm/brotli"
  14. )
  15. const compressionThreshold = 1024
  16. // Builder generates HTTP responses.
  17. type Builder struct {
  18. w http.ResponseWriter
  19. r *http.Request
  20. statusCode int
  21. headers map[string]string
  22. enableCompression bool
  23. body any
  24. }
  25. // NewBuilder creates a new response builder.
  26. func NewBuilder(w http.ResponseWriter, r *http.Request) *Builder {
  27. return &Builder{w: w, r: r, statusCode: http.StatusOK, headers: make(map[string]string), enableCompression: true}
  28. }
  29. // WithStatus uses the given status code to build the response.
  30. func (b *Builder) WithStatus(statusCode int) *Builder {
  31. b.statusCode = statusCode
  32. return b
  33. }
  34. // WithHeader adds the given HTTP header to the response.
  35. func (b *Builder) WithHeader(key, value string) *Builder {
  36. b.headers[key] = value
  37. return b
  38. }
  39. // WithBodyAsBytes uses the given bytes to build the response.
  40. func (b *Builder) WithBodyAsBytes(body []byte) *Builder {
  41. b.body = body
  42. return b
  43. }
  44. // WithBodyAsString uses the given string to build the response.
  45. func (b *Builder) WithBodyAsString(body string) *Builder {
  46. b.body = body
  47. return b
  48. }
  49. // WithBodyAsReader uses the given reader to build the response.
  50. func (b *Builder) WithBodyAsReader(body io.Reader) *Builder {
  51. b.body = body
  52. return b
  53. }
  54. // WithAttachment forces the document to be downloaded by the web browser.
  55. func (b *Builder) WithAttachment(filename string) *Builder {
  56. b.headers["Content-Disposition"] = formatContentDisposition("attachment", filename)
  57. return b
  58. }
  59. // WithInline suggests an inline filename for the current response.
  60. func (b *Builder) WithInline(filename string) *Builder {
  61. b.headers["Content-Disposition"] = formatContentDisposition("inline", filename)
  62. return b
  63. }
  64. // WithoutCompression disables HTTP compression.
  65. func (b *Builder) WithoutCompression() *Builder {
  66. b.enableCompression = false
  67. return b
  68. }
  69. // WithCaching adds caching headers to the response.
  70. func (b *Builder) WithCaching(etag string, duration time.Duration, callback func(*Builder)) {
  71. etag = normalizeETag(etag)
  72. b.headers["ETag"] = etag
  73. b.headers["Cache-Control"] = "public, immutable"
  74. b.headers["Expires"] = time.Now().Add(duration).UTC().Format(http.TimeFormat)
  75. if ifNoneMatch(b.r.Header.Get("If-None-Match"), etag) {
  76. b.statusCode = http.StatusNotModified
  77. b.body = nil
  78. b.Write()
  79. } else {
  80. callback(b)
  81. }
  82. }
  83. // Write generates the HTTP response.
  84. func (b *Builder) Write() {
  85. if b.body == nil {
  86. b.writeHeaders()
  87. return
  88. }
  89. switch v := b.body.(type) {
  90. case []byte:
  91. b.compress(v)
  92. case string:
  93. b.compress([]byte(v))
  94. case io.Reader:
  95. // Compression not implemented in this case
  96. b.writeHeaders()
  97. _, err := io.Copy(b.w, v)
  98. if err != nil {
  99. slog.Error("Unable to write response body", slog.Any("error", err))
  100. }
  101. }
  102. }
  103. func (b *Builder) writeHeaders() {
  104. b.headers["X-Content-Type-Options"] = "nosniff"
  105. b.headers["X-Frame-Options"] = "DENY"
  106. b.headers["Referrer-Policy"] = "no-referrer"
  107. for key, value := range b.headers {
  108. b.w.Header().Set(key, value)
  109. }
  110. b.w.WriteHeader(b.statusCode)
  111. }
  112. func (b *Builder) compress(data []byte) {
  113. if b.enableCompression && len(data) > compressionThreshold {
  114. b.headers["Vary"] = "Accept-Encoding"
  115. acceptEncoding := b.r.Header.Get("Accept-Encoding")
  116. switch {
  117. case strings.Contains(acceptEncoding, "br"):
  118. b.headers["Content-Encoding"] = "br"
  119. b.writeHeaders()
  120. brotliWriter := brotli.NewWriterV2(b.w, brotli.DefaultCompression)
  121. brotliWriter.Write(data)
  122. brotliWriter.Close()
  123. return
  124. case strings.Contains(acceptEncoding, "gzip"):
  125. b.headers["Content-Encoding"] = "gzip"
  126. b.writeHeaders()
  127. gzipWriter := gzip.NewWriter(b.w)
  128. gzipWriter.Write(data)
  129. gzipWriter.Close()
  130. return
  131. case strings.Contains(acceptEncoding, "deflate"):
  132. b.headers["Content-Encoding"] = "deflate"
  133. b.writeHeaders()
  134. flateWriter, _ := flate.NewWriter(b.w, -1)
  135. flateWriter.Write(data)
  136. flateWriter.Close()
  137. return
  138. }
  139. }
  140. b.writeHeaders()
  141. b.w.Write(data)
  142. }
  143. func normalizeETag(etag string) string {
  144. etag = strings.TrimSpace(etag)
  145. if etag == "" {
  146. return ""
  147. }
  148. if strings.HasPrefix(etag, `"`) || strings.HasPrefix(etag, `W/"`) {
  149. return etag
  150. }
  151. return `"` + etag + `"`
  152. }
  153. func ifNoneMatch(headerValue, etag string) bool {
  154. if headerValue == "" || etag == "" {
  155. return false
  156. }
  157. if strings.TrimSpace(headerValue) == "*" {
  158. return true
  159. }
  160. // Weak ETag comparison: the opaque-tag (quoted string without W/ prefix) must match.
  161. return strings.Contains(headerValue, strings.TrimPrefix(etag, `W/`))
  162. }
  163. func formatContentDisposition(dispositionType, filename string) string {
  164. if filename == "" {
  165. return dispositionType
  166. }
  167. if value := mime.FormatMediaType(dispositionType, map[string]string{"filename": filename}); value != "" {
  168. return value
  169. }
  170. return dispositionType
  171. }