### Install Clean Env Go Package Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md This command installs the cleanenv package using the Go get command. It ensures you have the latest version of the library for your project. ```bash go get -u github.com/ilyakaznacheev/cleanenv ``` -------------------------------- ### Integration with Golang Flag Package Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Provides an example of how to integrate cleanenv with Go's standard `flag` package to generate command-line help messages for configuration variables. ```APIDOC ## Integration The package can be used with many other solutions. To make it more useful, we made some helpers. ### Flag You can use the cleanenv help together with Golang `flag` package. ```go // create some config structure var cfg config // create flag set using `flag` package fset := flag.NewFlagSet("Example", flag.ContinueOnError) // get config usage with wrapped flag usage fset.Usage = cleanenv.FUsage(fset.Output(), &cfg, nil, fset.Usage) fset.Parse(os.Args[1:]) ``` ``` -------------------------------- ### Get Environment Variable Descriptions Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Shows how to retrieve descriptions for environment variables to be used in help documentation, utilizing the `env-description` tag and `cleanenv.GetDescription`. ```APIDOC ## Get Environment Variable Descriptions You can get descriptions of all environment variables to use them in the help documentation. ```go import "github.com/ilyakaznacheev/cleanenv" type ConfigServer struct { Port string `env:"PORT" env-description:"server port"` Host string `env:"HOST" env-description:"server host"` } var cfg ConfigRemote help, err := cleanenv.GetDescription(&cfg, nil) if err != nil { // handle error ... } // help will contain: // Environment variables: // PORT server port // HOST server host ``` ``` -------------------------------- ### Get Environment Variable Descriptions in Go Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Shows how to retrieve descriptions for environment variables defined in a configuration struct. This is useful for generating help documentation. The `env-description` tag is used to provide the description text, and `cleanenv.GetDescription()` retrieves this information. ```go import "github.com/ilyakaznacheev/cleanenv" type ConfigServer struct { Port string `env:"PORT" env-description:"server port"` Host string `env:"HOST" env-description:"server host" } var cfg ConfigRemote help, err := cleanenv.GetDescription(&cfg, nil) if err != nil { // handle error } // help will contain formatted descriptions ``` -------------------------------- ### Custom Setter Interface for Complex Types in Go Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Implement the `Setter` interface to define custom parsing logic for complex types. The `SetValue` method handles the raw string input from environment variables, allowing for transformations and validations before assigning to the target type. This example demonstrates custom parsing for `Roles` (a slice of strings) and `Email` types. ```go package main import ( "fmt" "os" "strings" "github.com/ilyakaznacheev/cleanenv" ) // Custom type with Setter interface type Roles []string func (r *Roles) SetValue(s string) error { if s == "" { return fmt.Errorf("roles cannot be empty") } *r = strings.Split(s, " ") return nil } // Custom type that validates and transforms input type Email string func (e *Email) SetValue(s string) error { if !strings.Contains(s, "@") { return fmt.Errorf("invalid email format: %s", s) } *e = Email(strings.ToLower(s)) return nil } type Config struct { AdminEmail Email `env:"ADMIN_EMAIL"` UserRoles Roles `env:"USER_ROLES"` } func main() { os.Setenv("ADMIN_EMAIL", "Admin@Example.COM") os.Setenv("USER_ROLES", "admin editor viewer") var cfg Config err := cleanenv.ReadEnv(&cfg) if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } fmt.Printf("Admin Email: %s\n", cfg.AdminEmail) fmt.Printf("User Roles: %v\n", cfg.UserRoles) } // Output: Admin Email: admin@example.com // User Roles: [admin editor viewer] ``` -------------------------------- ### Multiple Configuration Files Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Demonstrates how to load and merge multiple configuration files sequentially, allowing for hierarchical overrides. ```APIDOC ## Multiple Configuration Files ### Description This approach allows loading configuration from multiple files (e.g., defaults, environment-specific, and secrets) where later files override values from earlier ones. ### Method N/A (Library Function) ### Endpoint `cleanenv.ReadConfig(path string, cfg interface{})` ### Parameters #### Path Parameters - **path** (string) - Required - Path to the YAML/JSON configuration file. #### Request Body - **cfg** (struct) - Required - A pointer to the configuration struct to be populated. ### Request Example ```go cleanenv.ReadConfig("config/defaults.yml", &cfg) cleanenv.ReadConfig("config/secrets.yml", &cfg) ``` ### Response #### Success Response (200) - **cfg** (struct) - Merged configuration object. ``` -------------------------------- ### Read Configuration from File and Environment Variables Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Demonstrates how to use ReadConfig to parse a configuration file and override values with environment variables. It showcases the use of struct tags to define mappings and default values. ```go package main import ( "fmt" "os" "github.com/ilyakaznacheev/cleanenv" ) type Config struct { Database struct { Host string `yaml:"host" env:"DB_HOST" env-default:"localhost"` Port string `yaml:"port" env:"DB_PORT" env-default:"5432"` Username string `yaml:"username" env:"DB_USER" env-default:"user"` Password string `env:"DB_PASSWORD" env-description:"Database password"` Name string `yaml:"db-name" env:"DB_NAME" env-default:"postgres"` Connections int `yaml:"connections" env:"DB_CONNECTIONS" env-default:"10"` } `yaml:"database"` Server struct { Host string `yaml:"host" env:"SRV_HOST,HOST" env-default:"localhost"` Port string `yaml:"port" env:"SRV_PORT,PORT" env-default:"8080"` } `yaml:"server"` } func main() { var cfg Config os.Setenv("DB_PASSWORD", "secretpassword") err := cleanenv.ReadConfig("config.yml", &cfg) if err != nil { fmt.Printf("Error reading config: %v\n", err) os.Exit(1) } fmt.Printf("Database: %s@%s:%s/%s\n", cfg.Database.Username, cfg.Database.Host, cfg.Database.Port, cfg.Database.Name) fmt.Printf("Server: %s:%s\n", cfg.Server.Host, cfg.Server.Port) } ``` -------------------------------- ### Read Configuration from Multiple Files in Go Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Illustrates how to load configuration from multiple files sequentially using cleanenv. Later files override values from earlier ones. This function requires the 'fmt', 'os', and 'github.com/ilyakaznacheev/cleanenv' packages. It takes a configuration struct pointer and a variable number of file paths as input, returning an error if any file cannot be read. ```go package main import ( "fmt" "os" "github.com/ilyakaznacheev/cleanenv" ) type Config struct { Port string `yaml:"port" env:"PORT"` JWTSecret string `yaml:"jwt_secret" env:"JWT_SECRET"` DatabaseHost string `yaml:"db_host" env:"DB_HOST"` DatabaseName string `yaml:"db_name" env:"DB_NAME"` EmailAPIKey string `yaml:"email_key" env:"EMAIL_KEY"` } func ParseConfigFiles(cfg *Config, files ...string) error { for _, file := range files { if err := cleanenv.ReadConfig(file, cfg); err != nil { return fmt.Errorf("error reading %s: %w", file, err) } } return nil } func main() { var cfg Config err := ParseConfigFiles(&cfg, "config/defaults.yml", "config/database.yml", "config/secrets.yml", ) if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } fmt.Printf("Config: %+v\n", cfg) } ``` -------------------------------- ### Read Configuration from Environment Variables Only Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Demonstrates how to use ReadEnv to populate a configuration struct directly from environment variables. This is ideal for containerized environments where configuration is injected via the environment. ```go package main import ( "fmt" "net/url" "os" "time" "github.com/ilyakaznacheev/cleanenv" ) type Config struct { Port string `env:"PORT" env-default:"5432"` Host string `env:"HOST" env-default:"localhost"` Name string `env:"NAME" env-default:"postgres"` User string `env:"USER" env-default:"user"` Password string `env:"PASSWORD"` TTL time.Duration `env:"TTL" env-default:"30s"` DB url.URL `env:"DB_URL"` StartTime time.Time `env:"START_TIME" env-layout:"2006-01-02"` } func main() { os.Setenv("PORT", "5050") os.Setenv("NAME", "redis") os.Setenv("USER", "tester") os.Setenv("PASSWORD", "secret123") os.Setenv("TTL", "5m30s") os.Setenv("DB_URL", "postgres://user:pass@localhost:5432/mydb") os.Setenv("START_TIME", "2024-01-15") var cfg Config err := cleanenv.ReadEnv(&cfg) if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } fmt.Printf("Config: %+v\n", cfg) fmt.Printf("TTL: %v, DB Host: %s\n", cfg.TTL, cfg.DB.Host) } ``` -------------------------------- ### Usage and FUsage Functions Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Wraps standard Go flag usage functions to append environment variable documentation to the help output. ```APIDOC ## FUsage ### Description Wraps an existing flag usage function to include environment variable descriptions, allowing for unified CLI help output. ### Method Function Call ### Parameters - **output** (io.Writer) - Required - The writer to output the usage text to. - **cfg** (interface{}) - Required - The configuration struct to document. - **header** (*string) - Optional - Custom header text. - **usage** (func()) - Required - The original flag usage function to wrap. ### Response - **func()** - A wrapped function that prints both flag and environment variable help. ``` -------------------------------- ### Custom Value Update Implementation in Go Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Demonstrates how to implement a custom update logic for a configuration structure by implementing the `Updater` interface. This is useful for scenarios like loading remote configurations. The `Update` method can contain custom logic to fetch and apply updated values. ```go type Config struct { Field string } func (c *Config) Update() error { newField, err := SomeCustomUpdate() // Assume SomeCustomUpdate fetches new data c.Field = newField return err } ``` -------------------------------- ### Parsing Slices and Maps Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Demonstrates how to parse environment variables into Go slices and maps using custom separators. ```APIDOC ## Parsing Slices and Maps ### Description This functionality allows mapping comma-separated environment variables into slices and colon-separated key-value pairs into maps. Custom separators can be defined using the `env-separator` tag. ### Method N/A (Library Function) ### Endpoint `cleanenv.ReadEnv(cfg interface{})` ### Parameters #### Request Body - **cfg** (struct) - Required - A pointer to a struct containing `env` tags defining the mapping rules. ### Request Example ```go type Config struct { AllowedHosts []string `env:"ALLOWED_HOSTS"` Headers map[string]string `env:"HEADERS"` } ``` ### Response #### Success Response (200) - **cfg** (struct) - Populated struct with parsed environment values. #### Response Example ```go // Allowed Hosts: [api.example.com web.example.com] // Headers: map[X-Custom-Header:value1] ``` ``` -------------------------------- ### GetDescription Function Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Generates a formatted string containing all environment variables defined in a configuration struct, including types, descriptions, and default values. ```APIDOC ## GetDescription ### Description Generates a human-readable description of the environment variables defined in the struct, useful for CLI help text or documentation. ### Method Function Call ### Parameters - **cfg** (interface{}) - Required - The configuration struct to inspect. - **header** (*string) - Optional - A custom header string to prepend to the output. ### Response - **string** - A formatted string listing variables, types, descriptions, and defaults. ``` -------------------------------- ### Integrating Cleanenv with Go Flag Package Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Shows how to integrate cleanenv with Go's standard `flag` package for command-line argument parsing. `cleanenv.FUsage` can wrap the flag set's `Usage` function to automatically generate help messages based on the configuration structure. ```go import ( "flag" "github.com/ilyakaznacheev/cleanenv" ) // create some config structure var cfg config // create flag set using `flag` package fset := flag.NewFlagSet("Example", flag.ContinueOnError) // get config usage with wrapped flag usage fset.Usage = cleanenv.FUsage(fset.Output(), &cfg, nil, fset.Usage) fset.Parse(os.Args[1:]) ``` -------------------------------- ### GetDescription: Generate environment variable descriptions in Go Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt The GetDescription function generates a formatted description of all environment variables defined in a configuration structure. It includes variable types, descriptions, and default values, making it ideal for generating help text or documentation. It can accept a custom header string. ```go package main import ( "fmt" "github.com/ilyakaznacheev/cleanenv" ) type Config struct { Port string `env:"PORT" env-description:"Server port" env-default:"8080"` Host string `env:"HOST" env-description:"Server host" env-default:"localhost"` LogLevel string `env:"LOG_LEVEL" env-description:"Logging level (debug, info, warn, error)" env-default:"info"` Workers int `env:"WORKERS" env-description:"Number of worker threads" env-default:"4"` Debug bool `env:"DEBUG" env-description:"Enable debug mode"` } func main() { var cfg Config // Default header text, _ := cleanenv.GetDescription(&cfg, nil) fmt.Println(text) // Custom header customHeader := "Available Configuration:" text, _ = cleanenv.GetDescription(&cfg, &customHeader) fmt.Println("\n" + text) } // Output: // Environment variables: // DEBUG bool // Enable debug mode // HOST string // Server host (default "localhost") // LOG_LEVEL string // Logging level (debug, info, warn, error) (default "info") // PORT string // Server port (default "8080") // WORKERS int // Number of worker threads (default "4") // // Available Configuration: // DEBUG bool // Enable debug mode // ... ``` -------------------------------- ### Read Configuration File and Environment Variables in Go Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Demonstrates how to read configuration from a YAML file and overwrite values with environment variables using cleanenv. It utilizes struct tags for mapping file keys, environment variable names, and default values. This function is suitable for applications needing both file-based and environment-based configuration. ```go import "github.com/ilyakaznacheev/cleanenv" type ConfigDatabase struct { Port string `yaml:"port" env:"PORT" env-default:"5432" Host string `yaml:"host" env:"HOST" env-default:"localhost" Name string `yaml:"name" env:"NAME" env-default:"postgres" User string `yaml:"user" env:"USER" env-default:"user" Password string `yaml:"password" env:"PASSWORD" } var cfg ConfigDatabase err := cleanenv.ReadConfig("config.yml", &cfg) if err != nil { // Handle error } ``` -------------------------------- ### Usage and FUsage: Integrate env descriptions with flag usage in Go Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt The Usage and FUsage functions wrap existing flag usage functionalities to append environment variable descriptions. 'Usage' outputs to STDERR by default, while 'FUsage' allows specifying a custom writer. This is useful for providing comprehensive help messages that include both command-line flags and environment variables. ```go package main import ( "flag" "os" "github.com/ilyakaznacheev/cleanenv" ) type Config struct { Port string `env:"PORT" env-description:"Server port" env-default:"8080"` Host string `env:"HOST" env-description:"Server host" env-default:"localhost"` LogLevel string `env:"LOG_LEVEL" env-description:"Logging level" env-default:"info"` } func main() { var cfg Config fset := flag.NewFlagSet("myapp", flag.ContinueOnError) fset.String("c", "config.yml", "Path to configuration file") fset.Bool("v", false, "Enable verbose output") customHeader := "Environment Variables:" // Wrap flag usage with cleanenv description fset.Usage = cleanenv.FUsage(fset.Output(), &cfg, &customHeader, fset.Usage) fset.Parse(os.Args[1:]) } // Running: myapp -h // Output: // Usage of myapp: // -c string // Path to configuration file (default "config.yml") // -v Enable verbose output // // Environment Variables: // HOST string // Server host (default "localhost") // LOG_LEVEL string // Logging level (default "info") // PORT string // Server port (default "8080") ``` -------------------------------- ### Read Configuration with Environment Overrides in Go Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md This Go code snippet demonstrates how to read configuration from a YAML file and override its values with environment variables. It defines a Config struct with tags for YAML and environment variable mapping, then uses the ReadConfig function to load the configuration. Dependencies include the cleanenv library. Inputs are a file path and a pointer to the config struct. Outputs are the populated config struct and an error if parsing fails. Limitations may include the specific format of the config file and environment variable naming conventions. ```go type Config struct { Port string `yaml:"port" env:"PORT" env-default:"8080"` Host string `yaml:"host" env:"HOST" env-default:"localhost"` } var cfg Config err := ReadConfig("config.yml", &cfg) if err != nil { // Handle error ... } ``` -------------------------------- ### Custom Value Setter Implementation in Go Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Illustrates how to implement a custom setter for a type to allow it to be populated from environment variables. By implementing the `Setter` interface, you can define custom conversion logic from a string to your specific type. The `SetValue` method handles the conversion and error checking. ```go import "fmt" type MyField string func (f *MyField) SetValue(s string) error { if s == "" { return fmt.Errorf("field value can't be empty") } *f = MyField("my field is: " + s) return nil } type Config struct { Field MyField `env="MY_VALUE"` } ``` -------------------------------- ### Supported File Formats Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Lists the configuration file formats that the cleanenv library can parse, including YAML, JSON, TOML, EDN, and ENV. ```APIDOC ## Supported File Formats There are several most popular config file formats supported: - YAML (`.yaml`, `.yml`) - JSON (`.json`) - TOML (`.toml`) - EDN (`.edn`) - ENV (`.env`) **Note**: - while using `.env` file the library will set corresponding data to process environment variables. It will override existing variables with the same keys in the process environment. ``` -------------------------------- ### Parse Slices and Maps from Environment Variables in Go Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Demonstrates how to parse slices and maps from environment variables using the cleanenv library. It supports comma-separated values for slices and key-value pairs with custom separators for maps. Dependencies include the 'fmt', 'os', and 'github.com/ilyakaznacheev/cleanenv' packages. Input is read from environment variables, and output is printed to the console. ```go package main import ( "fmt" "os" "github.com/ilyakaznacheev/cleanenv" ) type Config struct { AllowedHosts []string `env:"ALLOWED_HOSTS" env-default:"localhost,127.0.0.1"` Ports []int `env:"PORTS"` Headers map[string]string `env:"HEADERS"` Timeouts map[string]int `env:"TIMEOUTS" env-separator:";"` } func main() { os.Setenv("ALLOWED_HOSTS", "api.example.com,web.example.com,admin.example.com") os.Setenv("PORTS", "8080,8081,8082") os.Setenv("HEADERS", "X-Custom-Header:value1,X-Api-Version:v2") os.Setenv("TIMEOUTS", "read:30;write:60;idle:120") var cfg Config err := cleanenv.ReadEnv(&cfg) if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } fmt.Printf("Allowed Hosts: %v\n", cfg.AllowedHosts) fmt.Printf("Ports: %v\n", cfg.Ports) fmt.Printf("Headers: %v\n", cfg.Headers) fmt.Printf("Timeouts: %v\n", cfg.Timeouts) } // Output: Allowed Hosts: [api.example.com web.example.com admin.example.com] // Ports: [8080 8081 8082] // Headers: map[X-Api-Version:v2 X-Custom-Header:value1] // Timeouts: map[idle:120 read:30 write:60] ``` -------------------------------- ### Model Format Tags Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Explains the various tags used in Go structs to configure how environment variables are parsed and managed by the cleanenv library. ```APIDOC ## Model Format Library uses tags to configure the model of configuration structure. There are the following tags: - `env=""` - environment variable name (e.g. `env="PORT"`); - `env-upd` - flag to mark a field as updatable. Run `UpdateEnv(&cfg)` to refresh updatable variables from environment; - `env-required` - flag to mark a field as required. If set will return an error during environment parsing when the flagged as required field is empty (default Go value). Tag `env-default` is ignored in this case; - `env-default=""` - default value. If the field wasn't filled from the environment variable default value will be used instead; - `env-separator=""` - custom list and map separator. If not set, the default separator `,` will be used; - `env-description=""` - environment variable description; - `env-layout=""` - parsing layout (for types like `time.Time`); - `env-prefix=""` - prefix for all fields of nested structure (only for nested structures); ``` -------------------------------- ### Read Environment Variables Only in Go Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Shows how to read configuration solely from environment variables using cleanenv. This is useful when configuration files are not desired or when using `.env` file formats. It relies on struct tags for environment variable names and default values. ```go import "github.com/ilyakaznacheev/cleanenv" type ConfigDatabase struct { Port string `env:"PORT" env-default:"5432" Host string `env:"HOST" env-default:"localhost" Name string `env:"NAME" env-default:"postgres" User string `env:"USER" env-default:"user" Password string `env:"PASSWORD" } var cfg ConfigDatabase err := cleanenv.ReadEnv(&cfg) if err != nil { // Handle error } ``` -------------------------------- ### Update Environment Variables Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Demonstrates how to mark environment variables as updatable and refresh their values during application runtime using `cleanenv.UpdateEnv`. ```APIDOC ## Update Environment Variables Some environment variables may change during the application run. To get the new values you need to mark these variables as updatable with the tag `env-upd` and then run the update function: ```go import "github.com/ilyakaznacheev/cleanenv" type ConfigRemote struct { Port string `env:"PORT" env-upd` Host string `env:"HOST" env-upd` UserName string `env:"USERNAME"` } var cfg ConfigRemote cleanenv.ReadEnv(&cfg) // ... some actions in-between err := cleanenv.UpdateEnv(&cfg) if err != nil { // handle error ... } ``` Here remote host and port may change in a distributed system architecture. Fields `cfg.Port` and `cfg.Host` can be updated in the runtime from corresponding environment variables. You can update them before the remote service call. Field `cfg.UserName` will not be changed after the initial read, though. ``` -------------------------------- ### Update Environment Variables in Go Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Demonstrates how to update specific environment variables during application runtime using the `env-upd` tag. This is useful for dynamically changing configurations like host or port in distributed systems. Fields marked with `env-upd` can be refreshed by calling `cleanenv.UpdateEnv()`. ```go import "github.com/ilyakaznacheev/cleanenv" type ConfigRemote struct { Port string `env:"PORT" env-upd` Host string `env:"HOST" env-upd` UserName string `env:"USERNAME" } var cfg ConfigRemote cleanenv.ReadEnv(&cfg) // ... some actions in-between err := cleanenv.UpdateEnv(&cfg) if err != nil { // handle error } ``` -------------------------------- ### Custom Value Setter Interface Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Explains how to implement the `Setter` interface to allow custom types to be set from environment variables. ```APIDOC ## Custom Value Setter To make custom type allows to set the value from the environment variable, you need to implement the `Setter` interface on the field level: ```go type MyField string func (f *MyField) SetValue(s string) error { if s == "" { return fmt.Errorf("field value can't be empty") } *f = MyField("my field is: "+ s) return nil } type Config struct { Field MyField `env="MY_VALUE"` } ``` `SetValue` method should implement conversion logic from string to custom type. ``` -------------------------------- ### Nested Structures with Environment Variable Prefixes in Go Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Organize configuration for nested structures using the `env-prefix` tag. This tag prepends a specified prefix to all environment variable names looked up for fields within that nested structure, allowing for clear namespacing and avoiding naming conflicts. Default values can still be applied to fields within nested structures. ```go package main import ( "fmt" "os" "github.com/ilyakaznacheev/cleanenv" ) type DatabaseConfig struct { Host string `env:"HOST" env-default:"localhost"` Port int `env:"PORT" env-default:"5432"` Username string `env:"USER"` Password string `env:"PASS"` } type CacheConfig struct { Host string `env:"HOST" env-default:"localhost"` Port int `env:"PORT" env-default:"6379"` TTL int `env:"TTL" env-default:"3600"` } type Config struct { Database DatabaseConfig `env-prefix:"DB_"` Cache CacheConfig `env-prefix:"CACHE_"` AppName string `env:"APP_NAME" env-default:"myapp"` } func main() { os.Setenv("DB_HOST", "db.example.com") os.Setenv("DB_USER", "admin") os.Setenv("DB_PASS", "secret") os.Setenv("CACHE_HOST", "redis.example.com") os.Setenv("CACHE_TTL", "7200") var cfg Config err := cleanenv.ReadEnv(&cfg) if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } fmt.Printf("Database: %s@%s:%d\n", cfg.Database.Username, cfg.Database.Host, cfg.Database.Port) fmt.Printf("Cache: %s:%d (TTL: %ds)\n", cfg.Cache.Host, cfg.Cache.Port, cfg.Cache.TTL) } // Output: Database: admin@db.example.com:5432 // Cache: redis.example.com:6379 (TTL: 7200s) ``` -------------------------------- ### Supported Types Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Lists the data types that the cleanenv library natively supports for parsing environment variables. ```APIDOC ## Supported types There are following supported types: - `int` (any kind); - `float` (any kind); - `string`; - `boolean`; - slices (of any other supported type); - maps (of any other supported type); - `time.Duration`; - `time.Time` (layout by default is RFC3339, may be overridden by `env-layout`); - `*time.Location` (time zone parsing [depends](https://pkg.go.dev/time#LoadLocation) on running machine); - any type that implements `encoding.TextUnmarshaler`; - any type implementing `cleanenv.Setter` interface. ``` -------------------------------- ### Updater Interface for Post-Read Logic in Go Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Implement the `Updater` interface on a configuration structure to execute custom logic after configuration values have been read. This is useful for tasks like fetching secrets from remote services or performing derived initializations. The `Update` method is called automatically by `ReadEnv` or `ReadConfig`. ```go package main import ( "fmt" "os" "github.com/ilyakaznacheev/cleanenv" ) type Config struct { APIKey string `env:"API_KEY"` SecretToken string // Not from env, set by Update() ServiceURL string // Not from env, set by Update() } // Update is called during ReadEnv/ReadConfig func (c *Config) Update() error { // Simulate fetching secrets from a vault or remote service c.SecretToken = "fetched-from-vault-" + c.APIKey[:4] c.ServiceURL = "https://api.example.com/v1" return nil } func main() { os.Setenv("API_KEY", "ak_live_1234567890") var cfg Config err := cleanenv.ReadEnv(&cfg) if err != nil { fmt.Printf("Error: %v\n", err) os.Exit(1) } fmt.Printf("API Key: %s\n", cfg.APIKey) fmt.Printf("Secret Token: %s\n", cfg.SecretToken) fmt.Printf("Service URL: %s\n", cfg.ServiceURL) } // Output: API Key: ak_live_1234567890 // Secret Token: fetched-from-vault-ak_l // Service URL: https://api.example.com/v1 ``` -------------------------------- ### UpdateEnv Function Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Re-reads environment variables marked with the 'env-upd' tag into a configuration structure, enabling dynamic runtime configuration updates. ```APIDOC ## UpdateEnv ### Description Updates specific fields in a configuration struct by re-reading environment variables that are tagged with `env-upd`. This allows for changing application settings without a restart. ### Method Function Call ### Parameters - **cfg** (interface{}) - Required - A pointer to the configuration structure to be updated. ### Request Example cleanenv.UpdateEnv(&cfg) ### Response - **void** - Updates the struct fields in-place. ``` -------------------------------- ### Custom Value Update Interface Source: https://github.com/ilyakaznacheev/cleanenv/blob/master/README.md Details how to implement the `Updater` interface on a struct level to execute custom logic when updating configuration values, such as loading remote configurations. ```APIDOC ## Custom Value Update You may need to execute some custom field update logic, e.g. for remote config load. Thus, you need to implement the `Updater` interface on the structure level: ```go type Config struct { Field string } func (c *Config) Update() error { newField, err := SomeCustomUpdate() f.Field = newField return err } ``` ``` -------------------------------- ### Required Fields and Default Values in Go Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt Enforce mandatory configuration values using the `env-required:"true"` tag. If a required field is not provided and has no default value, `cleanenv` will return an error. Default values can be specified using the `env-default` tag, which are applied if the environment variable is not set. ```go package main import ( "fmt" "os" "github.com/ilyakaznacheev/cleanenv" ) type Config struct { DatabaseURL string `env:"DATABASE_URL" env-required:"true"` APIKey string `env:"API_KEY" env-required:"true"` Port string `env:"PORT" env-default:"8080"` Debug bool `env:"DEBUG" env-default:"false"` } func main() { // Missing required DATABASE_URL os.Setenv("API_KEY", "secret-key") var cfg Config err := cleanenv.ReadEnv(&cfg) if err != nil { fmt.Printf("Configuration error: %v\n", err) os.Exit(1) } fmt.Printf("Config loaded: %+v\n", cfg) } // Output: Configuration error: field "DatabaseURL" is required but the value is not provided ``` -------------------------------- ### UpdateEnv: Re-read environment variables in Go Source: https://context7.com/ilyakaznacheev/cleanenv/llms.txt The UpdateEnv function re-reads environment variables marked with the 'env-upd' tag into the configuration structure. This is useful for dynamic configurations that can change during application runtime without requiring a restart. It only updates fields that have the 'env-upd' tag. ```go package main import ( "fmt" "os" "github.com/ilyakaznacheev/cleanenv" ) type Config struct { StaticValue int64 `env:"STATIC"` DynamicValue int64 `env:"DYNAMIC" env-upd:""` } func main() { // Initial environment setup os.Setenv("STATIC", "100") os.Setenv("DYNAMIC", "200") var cfg Config cleanenv.ReadEnv(&cfg) fmt.Printf("Initial: Static=%d, Dynamic=%d\n", cfg.StaticValue, cfg.DynamicValue) // Simulate environment change (e.g., from external config service) os.Setenv("STATIC", "999") os.Setenv("DYNAMIC", "500") // Update only updatable fields cleanenv.UpdateEnv(&cfg) fmt.Printf("Updated: Static=%d, Dynamic=%d\n", cfg.StaticValue, cfg.DynamicValue) } // Output: Initial: Static=100, Dynamic=200 // Updated: Static=100, Dynamic=500 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.