config.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package fetcher
  2. import (
  3. "errors"
  4. "time"
  5. "github.com/imgproxy/imgproxy/v3/config"
  6. "github.com/imgproxy/imgproxy/v3/ensure"
  7. "github.com/imgproxy/imgproxy/v3/version"
  8. )
  9. // Config holds the configuration for the image fetcher.
  10. type Config struct {
  11. // UserAgent is the User-Agent header to use when fetching images.
  12. UserAgent string
  13. // DownloadTimeout is the timeout for downloading an image, in seconds.
  14. DownloadTimeout time.Duration
  15. // MaxRedirects is the maximum number of redirects to follow when fetching an image.
  16. MaxRedirects int
  17. }
  18. // NewDefaultConfig returns a new Config instance with default values.
  19. func NewDefaultConfig() Config {
  20. return Config{
  21. UserAgent: "imgproxy/" + version.Version,
  22. DownloadTimeout: 5 * time.Second,
  23. MaxRedirects: 10,
  24. }
  25. }
  26. // LoadConfigFromEnv loads config variables from env
  27. func LoadConfigFromEnv(c *Config) (*Config, error) {
  28. c = ensure.Ensure(c, NewDefaultConfig)
  29. c.UserAgent = config.UserAgent
  30. c.DownloadTimeout = time.Duration(config.DownloadTimeout) * time.Second
  31. c.MaxRedirects = config.MaxRedirects
  32. return c, nil
  33. }
  34. // Validate checks config for errors
  35. func (c *Config) Validate() error {
  36. if len(c.UserAgent) == 0 {
  37. return errors.New("user agent cannot be empty")
  38. }
  39. if c.DownloadTimeout <= 0 {
  40. return errors.New("download timeout must be greater than 0")
  41. }
  42. return nil
  43. }