builder.go 4.5 KB

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