From 64b131f7f5db022fb043e291f0534a15c4dd4829 Mon Sep 17 00:00:00 2001 From: SimePel Date: Sun, 15 Jul 2018 21:09:44 +0700 Subject: [PATCH] add separate function for loading env values from file --- cmd/fathom/main.go | 3 ++- pkg/config/config.go | 59 +++++++++++++++++++++----------------------- 2 files changed, 30 insertions(+), 32 deletions(-) diff --git a/cmd/fathom/main.go b/cmd/fathom/main.go index aab41d7..bdaff3f 100644 --- a/cmd/fathom/main.go +++ b/cmd/fathom/main.go @@ -54,7 +54,8 @@ func main() { func before(c *cli.Context) error { configFile := c.String("config") - app.config = config.Parse(configFile) + LoadEnv(configFile) + app.config = config.Parse() app.database = datastore.New(app.config.Database) return nil } diff --git a/pkg/config/config.go b/pkg/config/config.go index a23df8f..b288116 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -17,40 +17,37 @@ type Config struct { Secret string } -// Parses the supplied file + environment into a Config struct -func Parse(file string) *Config { - var cfg Config - var err error - - if file != "" { - absfile, _ := filepath.Abs(file) - - // check if file exists - _, err := os.Stat(absfile) - fileNotExists := os.IsNotExist(err) - - if file == ".env" && fileNotExists { - log.Warnf("Missing configuration file. Using defaults.") - } else { - log.Printf("Configuration file: %s", absfile) - } - - if fileNotExists { - if file != ".env" { - log.Fatalf("Error reading configuration. File `%s` does not exist.", file) - } - } else { - // read file into env values - err = godotenv.Load(absfile) - if err != nil { - log.Fatalf("Error parsing configuration file: %s", err) - } - } - +// LoadEnv loads env values from the supplied file +func LoadEnv(file string) { + if file == "" { + log.Warn("Missing configuration file. Using defaults.") + return } + absFile, _ := filepath.Abs(file) + _, err := os.Stat(absFile) + fileNotExists := os.IsNotExist(err) + + if fileNotExists { + log.Warnf("Error reading configuration. File `%s` does not exist.", file) + return + } + + log.Printf("Configuration file: %s", absFile) + + // read file into env values + err = godotenv.Load(absFile) + if err != nil { + log.Fatalf("Error parsing configuration file: %s", err) + } +} + +// Parse environment into a Config struct +func Parse() *Config { + var cfg Config + // with config file loaded into env values, we can now parse env into our config struct - err = envconfig.Process("Fathom", &cfg) + err := envconfig.Process("Fathom", &cfg) if err != nil { log.Fatalf("Error parsing configuration from environment: %s", err) }