builder.go 5.2 KB

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