github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/config/config.go (about) 1 package config 2 3 // Config represents a generic configuration with metadata 4 // using which the configuration can be retrieved from a data source 5 // using a data source specific adapter. Example: Environment 6 type Config[T any] struct { 7 Name string 8 Default T 9 10 // The configuration value must be available in the data source 11 // otherwise an error is returned. 12 MustSupply bool 13 14 // The repository to be used for retrieving the value 15 // by default. If not provided, the environment repository 16 // is used. 17 Repository ConfigRepository[T] 18 } 19 20 // ConfigRepository defines the contract for implementing data source 21 // specific configuration adapters. This is used to retrieve the configuration 22 type ConfigRepository[T any] interface { 23 GetConfig(*Config[T]) (T, error) 24 } 25 26 // ConfigEncoder defines the contract for implementing configuration 27 // encoders so that any complex type can be encoded into string for storage 28 // and decoded back to the original type. 29 type ConfigEncoder[T any] interface { 30 Encode(T) (string, error) 31 Decode(string) (T, error) 32 } 33 34 // Common configurations that spans across multiple services 35 // and are generally independ of domain specific configurations. 36 var ( 37 AppServiceName = Config[string]{Name: "APP_SERVICE_NAME"} 38 AppServiceEnv = Config[string]{Name: "APP_SERVICE_ENV"} 39 AppLogFile = Config[string]{Name: "APP_LOG_FILE"} 40 AppLogLevel = Config[string]{Name: "APP_LOG_LEVEL"} 41 ) 42 43 // Helper function to access the value of a configuration 44 // using the default repository 45 func (c *Config[T]) Value() (T, error) { 46 var err error 47 r := c.Repository 48 49 if r == nil { 50 r, err = NewEnvironmentRepository(EnvironmentRepositoryConfig[T]{ 51 Encoder: NewStrconvConfigEncoder[T](), 52 }) 53 if err != nil { 54 return c.Default, err 55 } 56 } 57 58 return r.GetConfig(c) 59 } 60 61 // Helper function to access the value of a configuration 62 // using a specific repository 63 func (c *Config[T]) ValueFrom(r ConfigRepository[T]) (T, error) { 64 return r.GetConfig(c) 65 }