handler.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package stream
  2. import (
  3. "context"
  4. "io"
  5. "net/http"
  6. "sync"
  7. "github.com/imgproxy/imgproxy/v3/cookies"
  8. "github.com/imgproxy/imgproxy/v3/headerwriter"
  9. "github.com/imgproxy/imgproxy/v3/httpheaders"
  10. "github.com/imgproxy/imgproxy/v3/ierrors"
  11. "github.com/imgproxy/imgproxy/v3/imagefetcher"
  12. "github.com/imgproxy/imgproxy/v3/monitoring"
  13. "github.com/imgproxy/imgproxy/v3/monitoring/stats"
  14. "github.com/imgproxy/imgproxy/v3/options"
  15. "github.com/imgproxy/imgproxy/v3/server"
  16. log "github.com/sirupsen/logrus"
  17. )
  18. const (
  19. streamBufferSize = 4096 // Size of the buffer used for streaming
  20. categoryStreaming = "streaming" // Streaming error category
  21. )
  22. var (
  23. // streamBufPool is a sync.Pool for reusing byte slices used for streaming
  24. streamBufPool = sync.Pool{
  25. New: func() any {
  26. buf := make([]byte, streamBufferSize)
  27. return &buf
  28. },
  29. }
  30. )
  31. // Handler handles image passthrough requests, allowing images to be streamed directly
  32. type Handler struct {
  33. config *Config // Configuration for the streamer
  34. fetcher *imagefetcher.Fetcher // Fetcher instance to handle image fetching
  35. hw *headerwriter.Writer // Configured HeaderWriter instance
  36. }
  37. // request holds the parameters and state for a single streaming request
  38. type request struct {
  39. handler *Handler
  40. imageRequest *http.Request
  41. imageURL string
  42. reqID string
  43. po *options.ProcessingOptions
  44. rw http.ResponseWriter
  45. }
  46. // New creates new handler object
  47. func New(config *Config, hw *headerwriter.Writer, fetcher *imagefetcher.Fetcher) (*Handler, error) {
  48. if err := config.Validate(); err != nil {
  49. return nil, err
  50. }
  51. return &Handler{
  52. fetcher: fetcher,
  53. config: config,
  54. hw: hw,
  55. }, nil
  56. }
  57. // Stream handles the image passthrough request, streaming the image directly to the response writer
  58. func (s *Handler) Execute(
  59. ctx context.Context,
  60. userRequest *http.Request,
  61. imageURL string,
  62. reqID string,
  63. po *options.ProcessingOptions,
  64. rw http.ResponseWriter,
  65. ) error {
  66. stream := &request{
  67. handler: s,
  68. imageRequest: userRequest,
  69. imageURL: imageURL,
  70. reqID: reqID,
  71. po: po,
  72. rw: rw,
  73. }
  74. return stream.execute(ctx)
  75. }
  76. // execute handles the actual streaming logic
  77. func (s *request) execute(ctx context.Context) error {
  78. stats.IncImagesInProgress()
  79. defer stats.DecImagesInProgress()
  80. defer monitoring.StartStreamingSegment(ctx)()
  81. // Passthrough request headers from the original request
  82. requestHeaders := s.getImageRequestHeaders()
  83. cookieJar, err := s.getCookieJar()
  84. if err != nil {
  85. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryStreaming))
  86. }
  87. // Build the request to fetch the image
  88. r, err := s.handler.fetcher.BuildRequest(ctx, s.imageURL, requestHeaders, cookieJar)
  89. if r != nil {
  90. defer r.Cancel()
  91. }
  92. if err != nil {
  93. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryStreaming))
  94. }
  95. // Send the request to fetch the image
  96. res, err := r.Send()
  97. if res != nil {
  98. defer res.Body.Close()
  99. }
  100. if err != nil {
  101. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryStreaming))
  102. }
  103. // Output streaming response headers
  104. hw := s.handler.hw.NewRequest(res.Header, s.imageURL)
  105. hw.Passthrough(s.handler.config.PassthroughResponseHeaders...) // NOTE: priority? This is lowest as it was
  106. hw.SetContentLength(int(res.ContentLength))
  107. hw.SetCanonical()
  108. hw.SetExpires(s.po.Expires)
  109. // Set the Content-Disposition header
  110. s.setContentDisposition(r.URL().Path, res, hw)
  111. // Write headers from writer
  112. hw.Write(s.rw)
  113. // Copy the status code from the original response
  114. s.rw.WriteHeader(res.StatusCode)
  115. // Write the actual data
  116. s.streamData(res)
  117. return nil
  118. }
  119. // getCookieJar returns non-empty cookie jar if cookie passthrough is enabled
  120. func (s *request) getCookieJar() (http.CookieJar, error) {
  121. if !s.handler.config.CookiePassthrough {
  122. return nil, nil
  123. }
  124. return cookies.JarFromRequest(s.imageRequest)
  125. }
  126. // getImageRequestHeaders returns a new http.Header containing only
  127. // the headers that should be passed through from the user request
  128. func (s *request) getImageRequestHeaders() http.Header {
  129. h := make(http.Header)
  130. httpheaders.CopyFromRequest(s.imageRequest, h, s.handler.config.PassthroughRequestHeaders)
  131. return h
  132. }
  133. // setContentDisposition writes the headers to the response writer
  134. func (s *request) setContentDisposition(imagePath string, serverResponse *http.Response, hw *headerwriter.Request) {
  135. // Try to set correct Content-Disposition file name and extension
  136. if serverResponse.StatusCode < 200 || serverResponse.StatusCode >= 300 {
  137. return
  138. }
  139. ct := serverResponse.Header.Get(httpheaders.ContentType)
  140. hw.SetContentDisposition(
  141. imagePath,
  142. s.po.Filename,
  143. "",
  144. ct,
  145. s.po.ReturnAttachment,
  146. )
  147. }
  148. // streamData copies the image data from the response body to the response writer
  149. func (s *request) streamData(res *http.Response) {
  150. buf := streamBufPool.Get().(*[]byte)
  151. defer streamBufPool.Put(buf)
  152. _, copyerr := io.CopyBuffer(s.rw, res.Body, *buf)
  153. server.LogResponse(
  154. s.reqID, s.imageRequest, res.StatusCode, nil,
  155. log.Fields{
  156. "image_url": s.imageURL,
  157. "processing_options": s.po,
  158. },
  159. )
  160. // We've got to skip logging here
  161. if copyerr != nil {
  162. panic(http.ErrAbortHandler)
  163. }
  164. }