1
0

config.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package fetcher
  2. import (
  3. "errors"
  4. "strings"
  5. "time"
  6. "github.com/imgproxy/imgproxy/v3/ensure"
  7. "github.com/imgproxy/imgproxy/v3/env"
  8. "github.com/imgproxy/imgproxy/v3/fetcher/transport"
  9. "github.com/imgproxy/imgproxy/v3/version"
  10. )
  11. var (
  12. IMGPROXY_USER_AGENT = env.Describe("IMGPROXY_USER_AGENT", "non-empty string")
  13. IMGPROXY_DOWNLOAD_TIMEOUT = env.Describe("IMGPROXY_DOWNLOAD_TIMEOUT", "seconds => 0")
  14. IMGPROXY_MAX_REDIRECTS = env.Describe("IMGPROXY_MAX_REDIRECTS", "integer > 0")
  15. )
  16. // Config holds the configuration for the image fetcher.
  17. type Config struct {
  18. // UserAgent is the User-Agent header to use when fetching images.
  19. UserAgent string
  20. // DownloadTimeout is the timeout for downloading an image, in seconds.
  21. DownloadTimeout time.Duration
  22. // MaxRedirects is the maximum number of redirects to follow when fetching an image.
  23. MaxRedirects int
  24. // Transport holds the configuration for the transport layer.
  25. Transport transport.Config
  26. }
  27. // NewDefaultConfig returns a new Config instance with default values.
  28. func NewDefaultConfig() Config {
  29. return Config{
  30. UserAgent: "imgproxy/" + version.Version,
  31. DownloadTimeout: 5 * time.Second,
  32. MaxRedirects: 10,
  33. Transport: transport.NewDefaultConfig(),
  34. }
  35. }
  36. // LoadConfigFromEnv loads config variables from env
  37. func LoadConfigFromEnv(c *Config) (*Config, error) {
  38. c = ensure.Ensure(c, NewDefaultConfig)
  39. _, trErr := transport.LoadConfigFromEnv(&c.Transport)
  40. err := errors.Join(
  41. trErr,
  42. env.String(&c.UserAgent, IMGPROXY_USER_AGENT),
  43. env.Duration(&c.DownloadTimeout, IMGPROXY_DOWNLOAD_TIMEOUT),
  44. env.Int(&c.MaxRedirects, IMGPROXY_MAX_REDIRECTS),
  45. )
  46. // Set the current version in the User-Agent string
  47. c.UserAgent = strings.ReplaceAll(c.UserAgent, "%current_version", version.Version)
  48. return c, err
  49. }
  50. // Validate checks config for errors
  51. func (c *Config) Validate() error {
  52. if len(c.UserAgent) == 0 {
  53. return IMGPROXY_USER_AGENT.ErrorEmpty()
  54. }
  55. if c.DownloadTimeout <= 0 {
  56. return IMGPROXY_DOWNLOAD_TIMEOUT.ErrorZeroOrNegative()
  57. }
  58. if c.MaxRedirects <= 0 {
  59. return IMGPROXY_MAX_REDIRECTS.ErrorZeroOrNegative()
  60. }
  61. return nil
  62. }