config.go 1.6 KB

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