Cosmos-Server/src/config.go

46 lines
1.1 KiB
Go
Raw Normal View History

2023-02-26 22:26:09 +00:00
package main
import (
"os"
"regexp"
"encoding/json"
2023-03-25 20:15:00 +00:00
"github.com/azukaar/cosmos-server/src/utils"
2023-02-26 22:26:09 +00:00
)
2023-03-10 20:59:56 +00:00
func LoadConfig() utils.Config {
configFile := utils.GetConfigFileName()
utils.Log("Using config file: " + configFile)
if utils.CreateDefaultConfigFileIfNecessary() {
utils.LoadBaseMainConfig(utils.DefaultConfig)
return utils.DefaultConfig
2023-02-26 22:26:09 +00:00
}
file, err := os.Open(configFile)
if err != nil {
2023-03-10 20:59:56 +00:00
utils.Fatal("Opening Config File: ", err)
2023-02-26 22:26:09 +00:00
}
defer file.Close()
decoder := json.NewDecoder(file)
2023-03-10 20:59:56 +00:00
config := utils.Config{}
2023-02-26 22:26:09 +00:00
err = decoder.Decode(&config)
// check file is not empty
if err != nil {
// check error is not empty
if err.Error() == "EOF" {
2023-03-10 20:59:56 +00:00
utils.Fatal("Reading Config File: File is empty.", err)
2023-02-26 22:26:09 +00:00
}
// get error string
errString := err.Error()
// replace string in error
m1 := regexp.MustCompile(`json: cannot unmarshal ([A-Za-z\.]+) into Go struct field ([A-Za-z\.]+) of type ([A-Za-z\.]+)`)
errString = m1.ReplaceAllString(errString, "Invalid JSON in config file.\n > Field $2 is wrong.\n > Type is $1 Should be $3")
2023-03-10 20:59:56 +00:00
utils.Fatal("Reading Config File: " + errString, err)
2023-02-26 22:26:09 +00:00
}
2023-03-10 20:59:56 +00:00
utils.LoadBaseMainConfig(config)
2023-02-26 22:26:09 +00:00
return config
}