73 lines
1.8 KiB
Go
73 lines
1.8 KiB
Go
package config
|
|
|
|
import (
|
|
"github.com/pelletier/go-toml/v2"
|
|
"os"
|
|
"io/ioutil"
|
|
"log"
|
|
)
|
|
|
|
type InstanceConfig struct {
|
|
Name string `toml:"name"`
|
|
Description string `toml:"description"`
|
|
Domain string `toml:"domain"`
|
|
Software string `toml:"software"`
|
|
}
|
|
type DatabaseConfig struct {
|
|
Host string `toml:"host"`
|
|
User string `toml:"user"`
|
|
Pass string `toml:"pass"`
|
|
DB string `toml:"db"`
|
|
}
|
|
|
|
type Config struct {
|
|
IsDefault bool `toml:"-"`
|
|
Instance InstanceConfig `toml:"instance"`
|
|
Database DatabaseConfig `toml:"database"`
|
|
}
|
|
|
|
/*
|
|
load config by path (filename),
|
|
if specified file does not exist, return the default config as hardcoded below.
|
|
*/
|
|
func LoadConfig(path string) (Config, error) {
|
|
// always have default config!
|
|
cfg := Config{
|
|
IsDefault : true,
|
|
Instance : InstanceConfig{
|
|
Name : "my-instance",
|
|
Description : "let's fucking goooo!",
|
|
Domain : "my.instance",
|
|
Software : "my-software",
|
|
},
|
|
Database : DatabaseConfig{
|
|
Host : "localhost",
|
|
User : "user",
|
|
Pass : "pass",
|
|
DB : "my-db",
|
|
},
|
|
}
|
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
|
// return default config file
|
|
log.Println("WARNING: no config file. using defaults only")
|
|
return cfg, nil
|
|
} else {
|
|
// load existing config file
|
|
file, err := os.Open(path)
|
|
if err!=nil {
|
|
return cfg, err
|
|
}
|
|
defer file.Close()
|
|
content, err := ioutil.ReadAll(file)
|
|
if err!=nil {
|
|
return cfg, err
|
|
}
|
|
err = toml.Unmarshal(content, &cfg)
|
|
if err!=nil {
|
|
cfg.IsDefault = false
|
|
return cfg, err
|
|
}
|
|
return cfg, nil
|
|
}
|
|
}
|