Skip to content

Commit

Permalink
Add multi-file configuration read example
Browse files Browse the repository at this point in the history
  • Loading branch information
ilyakaznacheev committed Oct 4, 2020
2 parents 79220a7 + 5df00cf commit a188ca0
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 0 deletions.
5 changes: 5 additions & 0 deletions example/parse_multiple_files/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Parse multiple files for configuration

This example shows how the package can be used to read from mutiple configuration files and assign them to the same structure.

In this example, the configuration is read from ```db_config.yaml```,```email_config.yaml``` and ```general_config.yaml``` and the values are stored in the ```config``` struct.
7 changes: 7 additions & 0 deletions example/parse_multiple_files/db_config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
database:
host: "localhost"
user: "root"
password: "password"
name: "cleanenv"
port: "5432"
ssl_mode: "disable"
3 changes: 3 additions & 0 deletions example/parse_multiple_files/email_config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
email_service:
email_key: "RANDOM_KEY"
account_validation_template_id: "template_id"
2 changes: 2 additions & 0 deletions example/parse_multiple_files/general_config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
port: "8888"
jwt_secret: "RANDOM_SECRET"
55 changes: 55 additions & 0 deletions example/parse_multiple_files/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package main

import (
"log"

"github.com/ilyakaznacheev/cleanenv"
)

type config struct {
Port string `yaml:"port"`
JWTSecret string `yaml:"jwt_secret"`
Database databaseConfig `yaml:"database"`
EmailService emailService `yaml:"email_service"`
}

type databaseConfig struct {
User string `yaml:"user"`
Password string `yaml:"password"`
Name string `yaml:"name"`
Host string `yaml:"host"`
Port string `yaml:"port"`
SSLMode string `yaml:"ssl_mode"`
}

type emailService struct {
EmailKey string `yaml:"email_key"`
AccountValidationTemplateID string `yaml:"account_validation_template_id"`
}

func main() {
cfg, err := ParseConfigFiles("./db_config.yaml", "./email_config.yaml", "./general_config.yaml")
if err != nil {
log.Printf("Error parsing config files: %v", err)
return
}

log.Println("Parsed Configuration")
log.Println(*cfg)

return
}

func ParseConfigFiles(files ...string) (*config, error) {
var cfg config

for i := 0; i < len(files); i++ {
err := cleanenv.ReadConfig(files[i], &cfg)
if err != nil {
log.Printf("Error reading configuration from file:%v", files[i])
return nil, err
}
}

return &cfg, nil
}

0 comments on commit a188ca0

Please sign in to comment.