|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + |
| 8 | + "github.com/caarlos0/env/v6" |
| 9 | + "github.com/joho/godotenv" |
| 10 | + "go.yaml.in/yaml/v4" |
| 11 | +) |
| 12 | + |
| 13 | +func LoadConfig(path string) (*ApiConfig, error) { |
| 14 | + yamlFile, err := os.ReadFile(path) |
| 15 | + if err != nil { |
| 16 | + return nil, err |
| 17 | + } |
| 18 | + var config ApiConfig |
| 19 | + err = yaml.Unmarshal(yamlFile, &config) |
| 20 | + if err != nil { |
| 21 | + return nil, err |
| 22 | + } |
| 23 | + // check if any of the fields are empty |
| 24 | + if config.Host == "" { |
| 25 | + config.Host = "localhost" |
| 26 | + } |
| 27 | + if config.Port == 0 { |
| 28 | + config.Port = 8080 |
| 29 | + } |
| 30 | + // any cors method should be auto filled by the cors middleware |
| 31 | + // TODO: maybe add more options later |
| 32 | + return &config, nil |
| 33 | +} |
| 34 | + |
| 35 | +func LoadEnvironment(path string) (*ApiEnv, error) { |
| 36 | + possibleEnvFiles := []string{ |
| 37 | + ".env", // accept only .env for now |
| 38 | + } |
| 39 | + // check if any of the files exist within the current path |
| 40 | + existingFiles := []string{} |
| 41 | + for _, envFile := range possibleEnvFiles { |
| 42 | + formPath := filepath.Join(path, envFile) |
| 43 | + if _, err := os.Stat(formPath); err == nil { |
| 44 | + existingFiles = append(existingFiles, formPath) |
| 45 | + } |
| 46 | + } |
| 47 | + // if there are multiple files, decide which has highest priority |
| 48 | + // 1. production , 2. development, 3. local, 4. default |
| 49 | + // only use the regular .env for now return to this laster |
| 50 | + if len(existingFiles) == 0 { |
| 51 | + fmt.Println("No environment file found. Searching for os environment variables.") |
| 52 | + } else if len(existingFiles) == 1 { |
| 53 | + absPath, err := filepath.Abs(existingFiles[0]) |
| 54 | + if err != nil { |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + err = godotenv.Load(absPath) |
| 58 | + if err != nil { |
| 59 | + return nil, fmt.Errorf("error loading .env file: %w", err) |
| 60 | + } |
| 61 | + fmt.Printf("Loaded environment variables from %s\n", absPath) |
| 62 | + } |
| 63 | + |
| 64 | + environment := ApiEnv{} |
| 65 | + if err := env.Parse(&environment); err != nil { |
| 66 | + return nil, fmt.Errorf("failed to parse environment variables: %w", err) |
| 67 | + } |
| 68 | + |
| 69 | + return &environment, nil |
| 70 | +} |
0 commit comments