github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/config/repo.go (about) 1 package config 2 3 import ( 4 "fmt" 5 "os" 6 ) 7 8 // A base repository to hold common code, keeping things DRY 9 // at repository level 10 type baseRepository[T any] struct{} 11 12 func (b *baseRepository[T]) Default(c *Config[T]) (T, error) { 13 if c.MustSupply { 14 return c.Default, fmt.Errorf("config: %s is required", c.Name) 15 } 16 17 return c.Default, nil 18 } 19 20 type EnvironmentRepositoryConfig[T any] struct { 21 Prefix string 22 Encoder ConfigEncoder[T] 23 } 24 25 type environmentRepository[T any] struct { 26 baseRepository[T] 27 config EnvironmentRepositoryConfig[T] 28 } 29 30 func NewEnvironmentRepository[T any](config EnvironmentRepositoryConfig[T]) (ConfigRepository[T], error) { 31 if config.Encoder == nil { 32 config.Encoder = &JSONConfigEncoder[T]{} 33 } 34 35 return &environmentRepository[T]{config: config}, nil 36 } 37 38 func (e *environmentRepository[T]) GetConfig(c *Config[T]) (T, error) { 39 key := fmt.Sprintf("%s%s", e.config.Prefix, c.Name) 40 value := os.Getenv(key) 41 42 if value == "" { 43 return e.Default(c) 44 } 45 46 return e.config.Encoder.Decode(value) 47 }