config.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package responsewriter
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. "github.com/imgproxy/imgproxy/v3/config"
  7. "github.com/imgproxy/imgproxy/v3/ensure"
  8. )
  9. // Config holds configuration for response writer
  10. type Config struct {
  11. SetCanonicalHeader bool // Indicates whether to set the canonical header
  12. DefaultTTL int // Default Cache-Control max-age= value for cached images
  13. FallbackImageTTL int // TTL for images served as fallbacks
  14. CacheControlPassthrough bool // Passthrough the Cache-Control from the original response
  15. VaryValue string // Value for Vary header
  16. WriteResponseTimeout time.Duration // Timeout for response write operations
  17. }
  18. // NewDefaultConfig returns a new Config instance with default values.
  19. func NewDefaultConfig() Config {
  20. return Config{
  21. SetCanonicalHeader: false,
  22. DefaultTTL: 31536000,
  23. FallbackImageTTL: 0,
  24. CacheControlPassthrough: false,
  25. VaryValue: "",
  26. WriteResponseTimeout: 10 * time.Second,
  27. }
  28. }
  29. // LoadConfigFromEnv overrides configuration variables from environment
  30. func LoadConfigFromEnv(c *Config) (*Config, error) {
  31. c = ensure.Ensure(c, NewDefaultConfig)
  32. c.SetCanonicalHeader = config.SetCanonicalHeader
  33. c.DefaultTTL = config.TTL
  34. c.FallbackImageTTL = config.FallbackImageTTL
  35. c.CacheControlPassthrough = config.CacheControlPassthrough
  36. c.WriteResponseTimeout = time.Duration(config.WriteResponseTimeout) * time.Second
  37. vary := make([]string, 0)
  38. if c.envEnableFormatDetection() {
  39. vary = append(vary, "Accept")
  40. }
  41. if c.envEnableClientHints() {
  42. vary = append(vary, "Sec-CH-DPR", "DPR", "Sec-CH-Width", "Width")
  43. }
  44. c.VaryValue = strings.Join(vary, ", ")
  45. return c, nil
  46. }
  47. func (c *Config) envEnableFormatDetection() bool {
  48. return config.AutoWebp ||
  49. config.EnforceWebp ||
  50. config.AutoAvif ||
  51. config.EnforceAvif ||
  52. config.AutoJxl ||
  53. config.EnforceJxl
  54. }
  55. func (c *Config) envEnableClientHints() bool {
  56. return config.EnableClientHints
  57. }
  58. // Validate checks config for errors
  59. func (c *Config) Validate() error {
  60. if c.DefaultTTL < 0 {
  61. return fmt.Errorf("image TTL should be greater than or equal to 0, now - %d", c.DefaultTTL)
  62. }
  63. if c.FallbackImageTTL < 0 {
  64. return fmt.Errorf("fallback image TTL should be greater than or equal to 0, now - %d", c.FallbackImageTTL)
  65. }
  66. if c.WriteResponseTimeout <= 0 {
  67. return fmt.Errorf("write response timeout should be greater than 0, now - %d", c.WriteResponseTimeout)
  68. }
  69. return nil
  70. }