### Define Struct with envdecode Tags in Go Source: https://github.com/joeshaw/envdecode/blob/master/README.md This Go code snippet demonstrates how to define a struct with `env` struct tags for environment variable decoding. It shows how to specify environment variable names, default values, mark fields as required, and enable strict parsing. Fields must be exported (start with a capital letter) for envdecode to access them. ```go package main import ( "time" ) type Config struct { Hostname string `env:"SERVER_HOSTNAME,default=localhost"` Port uint16 `env:"SERVER_PORT,default=8080"` AWS struct { ID string `env:"AWS_ACCESS_KEY_ID"` Secret string `env:"AWS_SECRET_ACCESS_KEY,required"` SnsTopics []string `env:"AWS_SNS_TOPICS"` } Timeout time.Duration `env:"TIMEOUT,default=1m,strict"` } ``` -------------------------------- ### MustDecode: Decode or Terminate (Go) Source: https://context7.com/joeshaw/envdecode/llms.txt Calls Decode and terminates the process using a custom FailureFunc if any errors occur during decoding. This function is ideal for critical configuration values that must be present and valid for the application to start. ```go package main import ( "log" "github.com/joeshaw/envdecode" ) type RequiredConfig struct { DatabaseURL string `env:"DATABASE_URL,required"` APIKey string `env:"API_KEY,required"` Port int `env:"PORT,default=8080"` } func main() { // Custom failure handling (optional) envdecode.FailureFunc = func(err error) { log.Fatalf("FATAL: Configuration failed: %v", err) } var cfg RequiredConfig // Will terminate process if DATABASE_URL or API_KEY are not set envdecode.MustDecode(&cfg) log.Printf("Connected to: %s on port %d", cfg.DatabaseURL, cfg.Port) } // If DATABASE_URL is missing: // FATAL: Configuration failed: the environment variable "DATABASE_URL" is missing ``` -------------------------------- ### Export Configuration Metadata in Go Source: https://context7.com/joeshaw/envdecode/llms.txt Uses the Export function to retrieve detailed information about configuration fields, including their source (default vs environment), values, and requirements. This is ideal for logging and debugging application state. ```go package main import ( "fmt" "log" "os" "time" "github.com/joeshaw/envdecode" ) type AppConfig struct { Host string `env:"HOST,default=localhost"` Port int `env:"PORT,default=8080"` Timeout time.Duration `env:"TIMEOUT,default=30s"` LogLevel string `env:"LOG_LEVEL,required"` } func main() { os.Setenv("LOG_LEVEL", "debug") os.Setenv("PORT", "3000") var cfg AppConfig if err := envdecode.Decode(&cfg); err != nil { log.Fatal(err) } configInfo, err := envdecode.Export(&cfg) if err != nil { log.Fatal(err) } for _, ci := range configInfo { fmt.Printf("%s = %s (Source: %v)\n", ci.EnvVar, ci.Value, ci.UsesEnv) } } ``` -------------------------------- ### Implement nested struct configuration in Go Source: https://context7.com/joeshaw/envdecode/llms.txt Shows how to recursively decode environment variables into nested structs and pointers to structs. Pointers must be pre-allocated before calling the decode function. ```go package main import ( "fmt" "log" "os" "time" "github.com/joeshaw/envdecode" ) type DatabaseConfig struct { Host string `env:"DB_HOST,default=localhost"` Port int `env:"DB_PORT,default=5432"` Name string `env:"DB_NAME,required"` User string `env:"DB_USER,required"` Password string `env:"DB_PASSWORD,required"` SSLMode string `env:"DB_SSL_MODE,default=disable"` Pool PoolConfig Timeouts *TimeoutConfig } type PoolConfig struct { MaxOpen int `env:"DB_POOL_MAX_OPEN,default=25"` MaxIdle int `env:"DB_POOL_MAX_IDLE,default=5"` } type TimeoutConfig struct { Connect time.Duration `env:"DB_TIMEOUT_CONNECT,default=5s"` Query time.Duration `env:"DB_TIMEOUT_QUERY,default=30s"` } func main() { os.Setenv("DB_NAME", "myapp") os.Setenv("DB_USER", "admin") os.Setenv("DB_PASSWORD", "secret123") os.Setenv("DB_POOL_MAX_OPEN", "50") os.Setenv("DB_TIMEOUT_QUERY", "1m") cfg := DatabaseConfig{ Timeouts: &TimeoutConfig{}, } if err := envdecode.Decode(&cfg); err != nil { log.Fatalf("Failed to load config: %v", err) } fmt.Printf("Database: %s@%s:%d/%s\n", cfg.User, cfg.Host, cfg.Port, cfg.Name) fmt.Printf("SSL Mode: %s\n", cfg.SSLMode) fmt.Printf("Pool: max_open=%d, max_idle=%d\n", cfg.Pool.MaxOpen, cfg.Pool.MaxIdle) fmt.Printf("Timeouts: connect=%v, query=%v\n", cfg.Timeouts.Connect, cfg.Timeouts.Query) } ``` -------------------------------- ### Decode Environment Variables into Struct in Go Source: https://github.com/joeshaw/envdecode/blob/master/README.md This Go code snippet shows the basic usage of the `envdecode` package to populate a struct with values from environment variables. It first declares a struct variable and then calls `envdecode.Decode` to perform the decoding. Any parsing errors during the process will be returned. ```go package main import ( "github.com/joeshaw/envdecode" "time" ) type Config struct { Hostname string `env:"SERVER_HOSTNAME,default=localhost"` Port uint16 `env:"SERVER_PORT,default=8080"` Timeout time.Duration `env:"TIMEOUT,default=1m,strict"` } func main() { var cfg Config err := envdecode.Decode(&cfg) if err != nil { panic(err) } // Use cfg } ``` -------------------------------- ### Implement Custom Decoder Interface in Go Source: https://context7.com/joeshaw/envdecode/llms.txt Defines custom parsing logic for complex types by implementing the Decoder interface. This allows the library to handle non-primitive types like IP addresses or custom maps directly from environment strings. ```go package main import ( "fmt" "net" "strings" "github.com/joeshaw/envdecode" ) type IPAddress net.IP func (ip *IPAddress) Decode(value string) error { parsed := net.ParseIP(value) if parsed == nil { return fmt.Errorf("invalid IP address: %s", value) } *ip = IPAddress(parsed) return nil } type NetworkConfig struct { BindIP IPAddress `env:"BIND_IP,default=127.0.0.1"` } func main() { var cfg NetworkConfig envdecode.Decode(&cfg) fmt.Printf("Bind IP: %s", net.IP(cfg.BindIP)) } ``` -------------------------------- ### Strictly Decode Environment Variables in Go Source: https://github.com/joeshaw/envdecode/blob/master/README.md This Go code snippet demonstrates how to use `envdecode.StrictDecode` for a more rigorous decoding process. In this mode, all parsing errors will cause the function to fail fast and return an error immediately, ensuring that all configuration values are correctly parsed. ```go package main import ( "github.com/joeshaw/envdecode" "time" ) type Config struct { Hostname string `env:"SERVER_HOSTNAME,default=localhost"` Port uint16 `env:"SERVER_PORT,default=8080"` Timeout time.Duration `env:"TIMEOUT,default=1m,strict"` } func main() { var cfg Config err := envdecode.StrictDecode(&cfg) if err != nil { panic(err) } // Use cfg } ``` -------------------------------- ### Strictly Decode Environment Variables (Go) Source: https://context7.com/joeshaw/envdecode/llms.txt Decodes environment variables into a Go struct with strict parsing enabled. Any parsing errors will immediately return an error, preventing the use of zero values for invalid inputs. This is useful for ensuring configuration integrity at startup. ```go package main import ( "log" "time" "github.com/joeshaw/envdecode" ) type StrictConfig struct { Port int `env:"PORT,default=8080"` Timeout time.Duration `env:"TIMEOUT,default=5s"` MaxRetries int `env:"MAX_RETRIES,default=3"` } func main() { // If PORT is set to "invalid" (non-integer), StrictDecode will fail // os.Setenv("PORT", "invalid") var cfg StrictConfig if err := envdecode.StrictDecode(&cfg); err != nil { // With StrictDecode, parsing errors are returned immediately log.Fatalf("Configuration error: %v", err) } log.Printf("Port: %d, Timeout: %v, MaxRetries: %d", cfg.Port, cfg.Timeout, cfg.MaxRetries) } // If PORT="invalid": Configuration error: strconv.ParseInt: parsing "invalid": invalid syntax // If PORT="3000": Port: 3000, Timeout: 5s, MaxRetries: 3 ``` -------------------------------- ### Implement Custom Decoder Interface in Go Source: https://github.com/joeshaw/envdecode/blob/master/README.md This Go code snippet illustrates how to implement a custom decoder for a specific type using the `envdecode.Decoder` interface. It defines a `Config` struct with a custom `IPAddr` field and a `IP` type that implements the `Decode` method to handle IP address parsing from environment variables. ```go package main import ( "net" "github.com/joeshaw/envdecode" ) type Config struct { IPAddr IP `env:"IP_ADDR"` } type IP net.IP // Decode implements the interface `envdecode.Decoder` func (i *IP) Decode(repl string) error { *i = net.ParseIP(repl) return nil } func main() { var cfg Config err := envdecode.Decode(&cfg) if err != nil { panic(err) } // Use cfg.IPAddr } ``` -------------------------------- ### Perform Strict Environment Decoding in Go Source: https://context7.com/joeshaw/envdecode/llms.txt Uses MustStrictDecode to parse environment variables into a struct. It automatically terminates the process if required fields are missing or values fail to parse. ```go package main import ( "log" "time" "github.com/joeshaw/envdecode" ) type CriticalConfig struct { ConnectionTimeout time.Duration `env:"CONNECTION_TIMEOUT,required"` MaxConnections int `env:"MAX_CONNECTIONS,default=100"` EnableTLS bool `env:"ENABLE_TLS,default=true"` } func main() { var cfg CriticalConfig envdecode.MustStrictDecode(&cfg) log.Printf("Timeout: %v, MaxConn: %d, TLS: %v", cfg.ConnectionTimeout, cfg.MaxConnections, cfg.EnableTLS) } ``` -------------------------------- ### Decode Environment Variables into Structs (Go) Source: https://context7.com/joeshaw/envdecode/llms.txt Decodes environment variables into a Go struct using struct tags. Supports default values, required fields, and nested structs. The target must be a non-nil pointer to a struct with exported fields tagged with `env` struct tags. Returns an error if no fields are set or if required fields are missing. ```go package main import ( "fmt" "log" "net/url" "time" "github.com/joeshaw/envdecode" ) type Config struct { Hostname string `env:"SERVER_HOSTNAME,default=localhost"` Port uint16 `env:"SERVER_PORT,default=8080"` Debug bool `env:"DEBUG"` Timeout time.Duration `env:"TIMEOUT,default=30s"` APIUrl *url.URL `env:"API_URL,default=https://api.example.com"` AWS struct { AccessKeyID string `env:"AWS_ACCESS_KEY_ID,required"` SecretAccessKey string `env:"AWS_SECRET_ACCESS_KEY,required"` Region string `env:"AWS_REGION,default=us-east-1"` SnsTopics []string `env:"AWS_SNS_TOPICS"` } } func main() { // Set environment variables (normally done externally) // os.Setenv("AWS_ACCESS_KEY_ID", "AKIAIOSFODNN7EXAMPLE") // os.Setenv("AWS_SECRET_ACCESS_KEY", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY") // os.Setenv("AWS_SNS_TOPICS", "topic1;topic2;topic3") // os.Setenv("DEBUG", "true") var cfg Config if err := envdecode.Decode(&cfg); err != nil { log.Fatalf("Failed to decode config: %v", err) } fmt.Printf("Server: %s:%d\n", cfg.Hostname, cfg.Port) fmt.Printf("Debug: %v\n", cfg.Debug) fmt.Printf("Timeout: %v\n", cfg.Timeout) fmt.Printf("API URL: %s\n", cfg.APIUrl.String()) fmt.Printf("AWS Region: %s\n", cfg.AWS.Region) fmt.Printf("SNS Topics: %v\n", cfg.AWS.SnsTopics) } // Output (with defaults and AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY set): // Server: localhost:8080 // Debug: false // Timeout: 30s // API URL: https://api.example.com // AWS Region: us-east-1 // SNS Topics: [topic1 topic2 topic3] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.