config.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package config
  2. import (
  3. "fmt"
  4. "os"
  5. "strconv"
  6. "time"
  7. )
  8. type Config struct {
  9. Port int
  10. S3Endpoint string
  11. S3Region string
  12. S3Bucket string
  13. S3AccessKey string
  14. S3SecretKey string
  15. S3UsePathStyle bool
  16. PresignTTL time.Duration
  17. MaxUploadBytes int64
  18. CacheDir string
  19. ZipCacheDir string
  20. FeedDefaultSize int
  21. }
  22. func Load() (Config, error) {
  23. port := getenvInt("PORT", 8080)
  24. presignTTLSeconds := getenvInt("PRESIGN_TTL_SECONDS", 900)
  25. maxUploadBytes := getenvInt64("MAX_UPLOAD_BYTES", 1024*1024*1024)
  26. cacheDir := getenv("CACHE_DIR", ".cache/images")
  27. zipCacheDir := getenv("ZIP_CACHE_DIR", ".cache/zips")
  28. cfg := Config{
  29. Port: port,
  30. S3Endpoint: os.Getenv("S3_ENDPOINT"),
  31. S3Region: getenv("S3_REGION", "us-east-1"),
  32. S3Bucket: os.Getenv("S3_BUCKET"),
  33. S3AccessKey: os.Getenv("S3_ACCESS_KEY"),
  34. S3SecretKey: os.Getenv("S3_SECRET_KEY"),
  35. S3UsePathStyle: getenvBool("S3_USE_PATH_STYLE", true),
  36. PresignTTL: time.Duration(presignTTLSeconds) * time.Second,
  37. MaxUploadBytes: maxUploadBytes,
  38. CacheDir: cacheDir,
  39. ZipCacheDir: zipCacheDir,
  40. FeedDefaultSize: getenvInt("FEED_DEFAULT_LIMIT", 80),
  41. }
  42. if cfg.S3Bucket == "" {
  43. return Config{}, fmt.Errorf("S3_BUCKET is required")
  44. }
  45. if cfg.S3AccessKey == "" {
  46. return Config{}, fmt.Errorf("S3_ACCESS_KEY is required")
  47. }
  48. if cfg.S3SecretKey == "" {
  49. return Config{}, fmt.Errorf("S3_SECRET_KEY is required")
  50. }
  51. if cfg.S3Endpoint == "" {
  52. return Config{}, fmt.Errorf("S3_ENDPOINT is required")
  53. }
  54. return cfg, nil
  55. }
  56. func getenv(key string, fallback string) string {
  57. v := os.Getenv(key)
  58. if v == "" {
  59. return fallback
  60. }
  61. return v
  62. }
  63. func getenvInt(key string, fallback int) int {
  64. v := os.Getenv(key)
  65. if v == "" {
  66. return fallback
  67. }
  68. n, err := strconv.Atoi(v)
  69. if err != nil {
  70. return fallback
  71. }
  72. return n
  73. }
  74. func getenvInt64(key string, fallback int64) int64 {
  75. v := os.Getenv(key)
  76. if v == "" {
  77. return fallback
  78. }
  79. n, err := strconv.ParseInt(v, 10, 64)
  80. if err != nil {
  81. return fallback
  82. }
  83. return n
  84. }
  85. func getenvBool(key string, fallback bool) bool {
  86. v := os.Getenv(key)
  87. if v == "" {
  88. return fallback
  89. }
  90. b, err := strconv.ParseBool(v)
  91. if err != nil {
  92. return fallback
  93. }
  94. return b
  95. }