Golang Implementation
Environment Variable Handling in Go
Basic Environment Variable Retrieval
package main
import (
"fmt"
"os"
)
func main() {
// Retrieve a specific environment variable
apiKey := os.Getenv("API_KEY")
// Check if variable exists
if apiKey == "" {
fmt.Println("API_KEY not set")
}
}
Secure Environment Variable Management
Safe Environment Variable Parsing
package main
import (
"log"
"os"
"strconv"
)
func getIntEnv(key string, defaultValue int) int {
valueStr := os.Getenv(key)
if valueStr == "" {
return defaultValue
}
value, err := strconv.Atoi(valueStr)
if err != nil {
log.Printf("Invalid %s value: %v", key, err)
return defaultValue
}
return value
}
Environment Variable Workflow
graph TD
A[Read Env Var] --> B{Var Exists?}
B -->|Yes| C[Validate Value]
B -->|No| D[Use Default]
C --> E[Process Value]
D --> E
Advanced Environment Management
Comprehensive Environment Handling
package main
import (
"fmt"
"os"
"strings"
)
type Config struct {
DatabaseURL string
LogLevel string
MaxRetries int
}
func loadConfig() Config {
return Config{
DatabaseURL: os.Getenv("DATABASE_URL"),
LogLevel: getLogLevel(),
MaxRetries: getMaxRetries(),
}
}
func getLogLevel() string {
level := os.Getenv("LOG_LEVEL")
validLevels := []string{"DEBUG", "INFO", "WARN", "ERROR"}
for _, valid := range validLevels {
if strings.ToUpper(level) == valid {
return level
}
}
return "INFO"
}
func getMaxRetries() int {
retriesStr := os.Getenv("MAX_RETRIES")
retries, err := strconv.Atoi(retriesStr)
if err != nil || retries < 0 {
return 3 // Default value
}
return retries
}
Environment Variable Best Practices
Practice |
Description |
Example |
Validation |
Always validate env vars |
Check type, range |
Default Values |
Provide fallback options |
defaultPort := 8080 |
Secure Handling |
Avoid exposing sensitive data |
Use secret management |
Logging |
Log configuration issues |
Warn about missing vars |
Secure Environment Loading Pattern
func initializeApplication() error {
requiredVars := []string{
"DATABASE_URL",
"API_KEY",
"LOG_LEVEL"
}
for _, varName := range requiredVars {
if os.Getenv(varName) == "" {
return fmt.Errorf("missing required env var: %s", varName)
}
}
return nil
}
LabEx Recommended Approach
At LabEx, we emphasize a robust approach to environment variable management:
- Always validate inputs
- Use strong typing
- Implement comprehensive error handling
- Provide clear default configurations
Error Handling Strategy
func loadSecureConfig() (*Config, error) {
config := &Config{}
if err := validateEnvironment(); err != nil {
return nil, fmt.Errorf("environment validation failed: %v", err)
}
config.DatabaseURL = os.Getenv("DATABASE_URL")
// Additional configuration loading
return config, nil
}
Key Takeaways
- Use
os.Getenv()
for variable retrieval
- Implement robust validation
- Provide default values
- Handle potential errors gracefully