Skip to content

Commit

Permalink
Let Viper handle the config file
Browse files Browse the repository at this point in the history
  • Loading branch information
maddie committed Nov 10, 2020
1 parent c815103 commit fc6e99b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 36 deletions.
35 changes: 7 additions & 28 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package config

import (
"os"

log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
Expand Down Expand Up @@ -30,6 +28,7 @@ type Config struct {
}

var (
configFile string = ""
loadedConfig *Config = nil
)

Expand All @@ -51,8 +50,12 @@ func init() {
viper.AddConfigPath(".")
}

func Load() Config {
func Load(configPath string) Config {
var conf Config

configFile = configPath
viper.SetConfigFile(configPath)

if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Warnf("No config file found in search paths, using default values")
Expand All @@ -70,33 +73,9 @@ func Load() Config {
return conf
}

func LoadFile(configFile string) Config {
var conf Config

f, err := os.OpenFile(configFile, os.O_RDONLY, 0444)

if err != nil {
log.Fatalf("Failed to open config file: %s", err)
}

defer f.Close()

if err := viper.ReadConfig(f); err != nil {
log.Fatalf("Error reading config: %s", err)
}

if err := viper.Unmarshal(&conf); err != nil {
log.Fatalf("Error parsing config: %s", err)
}

loadedConfig = &conf

return conf
}

func LoadedConfig() *Config {
if loadedConfig == nil {
Load()
Load(configFile)
}
return loadedConfig
}
9 changes: 1 addition & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,7 @@ var (

func main() {
flag.Parse()

var conf config.Config
if *optConfig != "" {
conf = config.LoadFile(*optConfig)
} else {
conf = config.Load()
}

conf := config.Load(*optConfig)
web.SetServerLocation(&conf)
results.Initialize(&conf)
database.SetDBInfo(&conf)
Expand Down

0 comments on commit fc6e99b

Please sign in to comment.