download.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package imagedata
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/imgproxy/imgproxy/v3/config"
  6. "github.com/imgproxy/imgproxy/v3/ierrors"
  7. "github.com/imgproxy/imgproxy/v3/imagefetcher"
  8. "github.com/imgproxy/imgproxy/v3/security"
  9. "github.com/imgproxy/imgproxy/v3/transport"
  10. )
  11. var (
  12. Fetcher *imagefetcher.Fetcher
  13. // For tests
  14. redirectAllRequestsTo string
  15. )
  16. type DownloadOptions struct {
  17. Header http.Header
  18. CookieJar http.CookieJar
  19. }
  20. func initDownloading() error {
  21. ts, err := transport.NewTransport()
  22. if err != nil {
  23. return err
  24. }
  25. Fetcher, err = imagefetcher.NewFetcher(ts, config.MaxRedirects)
  26. if err != nil {
  27. return ierrors.Wrap(err, 0, ierrors.WithPrefix("can't create image fetcher"))
  28. }
  29. return nil
  30. }
  31. func download(ctx context.Context, imageURL string, opts DownloadOptions, secopts security.Options) (ImageData, http.Header, error) {
  32. h := make(http.Header)
  33. // We use this for testing
  34. if len(redirectAllRequestsTo) > 0 {
  35. imageURL = redirectAllRequestsTo
  36. }
  37. req, err := Fetcher.BuildRequest(ctx, imageURL, opts.Header, opts.CookieJar)
  38. if err != nil {
  39. return nil, h, err
  40. }
  41. defer req.Cancel()
  42. res, err := req.FetchImage()
  43. if res != nil {
  44. h = res.Header.Clone()
  45. }
  46. if err != nil {
  47. if res != nil {
  48. res.Body.Close()
  49. }
  50. return nil, h, err
  51. }
  52. res, err = security.LimitResponseSize(res, secopts)
  53. if res != nil {
  54. defer res.Body.Close()
  55. }
  56. if err != nil {
  57. return nil, h, err
  58. }
  59. imgdata, err := readAndCheckImage(res.Body, int(res.ContentLength), secopts)
  60. if err != nil {
  61. return nil, h, ierrors.Wrap(err, 0)
  62. }
  63. return imgdata, h, nil
  64. }
  65. func RedirectAllRequestsTo(u string) {
  66. redirectAllRequestsTo = u
  67. }
  68. func StopRedirectingRequests() {
  69. redirectAllRequestsTo = ""
  70. }