diff --git a/server/main/config.go b/server/main/config.go index b70eeb125..e851f4446 100644 --- a/server/main/config.go +++ b/server/main/config.go @@ -1,9 +1,9 @@ package main import ( - "encoding/json" "log" - "os" + + "github.com/spf13/viper" ) // Configuration is the app configuration stored in a json file @@ -17,49 +17,30 @@ type Configuration struct { FilesPath string `json:"filespath"` } -func readConfigFile() Configuration { - fileName := "config.json" - if !fileExists(fileName) { - log.Println(`config.json not found, using default settings`) - return Configuration{} +func readConfigFile() (*Configuration, error) { + viper.SetConfigName("config") // name of config file (without extension) + viper.SetConfigType("json") // REQUIRED if the config file does not have the extension in the name + viper.AddConfigPath(".") // optionally look for config in the working directory + viper.SetDefault("ServerRoot", "http://localhost") + viper.SetDefault("Port", 8000) + viper.SetDefault("DBType", "sqlite3") + viper.SetDefault("DBConfigString", "./octo.db") + viper.SetDefault("WebPath", "./pack") + viper.SetDefault("FilesPath", "./files") + + err := viper.ReadInConfig() // Find and read the config file + if err != nil { // Handle errors reading the config file + return nil, err } - file, _ := os.Open(fileName) - defer file.Close() - decoder := json.NewDecoder(file) configuration := Configuration{} - err := decoder.Decode(&configuration) + err = viper.Unmarshal(&configuration) if err != nil { - log.Fatal("Invalid config.json", err) - } - - // Apply defaults - if len(configuration.ServerRoot) < 1 { - configuration.ServerRoot = "http://localhost" - } - - if configuration.Port == 0 { - configuration.Port = 8000 - } - - if len(configuration.DBType) < 1 { - configuration.DBType = "sqlite3" - } - - if len(configuration.DBConfigString) < 1 { - configuration.DBConfigString = "./octo.db" - } - - if len(configuration.WebPath) < 1 { - configuration.WebPath = "./pack" - } - - if len(configuration.FilesPath) < 1 { - configuration.FilesPath = "./files" + return nil, err } log.Println("readConfigFile") log.Printf("%+v", configuration) - return configuration + return &configuration, nil } diff --git a/server/main/main.go b/server/main/main.go index 82f4a5786..b58b71aec 100644 --- a/server/main/main.go +++ b/server/main/main.go @@ -20,7 +20,7 @@ import ( "github.com/gorilla/websocket" ) -var config Configuration +var config *Configuration // WebsocketMsg is send on block changes type WebsocketMsg struct { @@ -383,7 +383,12 @@ func monitorPid(pid int) { func main() { // config.json file - config = readConfigFile() + var err error + config, err = readConfigFile() + if err != nil { + log.Fatal("Unable to read the config file: ", err) + return + } // Command line args pMonitorPid := flag.Int("monitorpid", -1, "a process ID")