LoadCLIConfig loads configuration from files, environment, and returns a merged config
(configPath string)
| 11 | |
| 12 | // LoadCLIConfig loads configuration from files, environment, and returns a merged config |
| 13 | func LoadCLIConfig(configPath string) (*CLIConfig, error) { |
| 14 | cfg := DefaultCLIConfig() |
| 15 | |
| 16 | // Initialize viper |
| 17 | v := viper.New() |
| 18 | v.SetConfigType("yaml") |
| 19 | |
| 20 | // Determine config file to use |
| 21 | var foundConfig bool |
| 22 | if configPath != "" { |
| 23 | // Use specific config file path if provided |
| 24 | v.SetConfigFile(configPath) |
| 25 | foundConfig = true |
| 26 | } else { |
| 27 | // Search for specific config files (not just any file named lambda-nat-proxy) |
| 28 | configFiles := []string{ |
| 29 | "./lambda-nat-proxy.yaml", // Current directory |
| 30 | "./lambda-nat-proxy.yml", // Current directory (alt extension) |
| 31 | filepath.Join(xdg.ConfigHome, "lambda-nat-proxy", "lambda-nat-proxy.yaml"), // User config |
| 32 | filepath.Join(xdg.ConfigHome, "lambda-nat-proxy", "lambda-nat-proxy.yml"), // User config (alt) |
| 33 | "/etc/lambda-nat-proxy/lambda-nat-proxy.yaml", // System directory |
| 34 | "/etc/lambda-nat-proxy/lambda-nat-proxy.yml", // System directory (alt) |
| 35 | } |
| 36 | |
| 37 | // Also check XDG config dirs |
| 38 | for _, dir := range xdg.ConfigDirs { |
| 39 | configFiles = append(configFiles, |
| 40 | filepath.Join(dir, "lambda-nat-proxy", "lambda-nat-proxy.yaml"), |
| 41 | filepath.Join(dir, "lambda-nat-proxy", "lambda-nat-proxy.yml"), |
| 42 | ) |
| 43 | } |
| 44 | |
| 45 | // Find the first existing config file |
| 46 | for _, configFile := range configFiles { |
| 47 | if _, err := os.Stat(configFile); err == nil { |
| 48 | v.SetConfigFile(configFile) |
| 49 | foundConfig = true |
| 50 | break |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // Try to read config file (only if one was found) |
| 56 | if foundConfig { |
| 57 | if err := v.ReadInConfig(); err != nil { |
| 58 | return nil, fmt.Errorf("error reading config file: %w", err) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | // Set environment variable prefix |
| 63 | v.SetEnvPrefix("LAMBDA_PROXY") |
| 64 | v.AutomaticEnv() |
| 65 | |
| 66 | // Map environment variables to config keys |
| 67 | v.BindEnv("aws.region", "AWS_REGION") |
| 68 | v.BindEnv("aws.profile", "AWS_PROFILE") |
| 69 | v.BindEnv("deployment.mode", "MODE") |
| 70 | v.BindEnv("proxy.port", "SOCKS5_PORT") |