habbgo/config/config.go

82 lines
1.6 KiB
Go
Raw Normal View History

package config
import (
"io/ioutil"
"log"
2021-09-06 01:07:49 +00:00
"os"
2022-01-08 22:29:51 +00:00
"gopkg.in/yaml.v2"
)
type Config struct {
2021-09-06 01:07:49 +00:00
Server *ServerCfg
DB *DatabaseCfg
}
type ServerCfg struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
MaxConns int `yaml:"maxconns"`
Debug bool `yaml:"debug"`
}
2021-09-06 01:07:49 +00:00
type DatabaseCfg struct {
User string `yaml:"user"`
Password string `yaml:"password"`
Host string `yaml:"host"`
Port int16 `yaml:"port"`
Name string `yaml:"name"`
}
2021-09-06 02:48:30 +00:00
func LoadConfig(file string) *Config {
2021-09-06 01:07:49 +00:00
c := &Config{}
2021-09-06 02:48:30 +00:00
data, err := ioutil.ReadFile(file)
2021-09-06 01:07:49 +00:00
if err != nil {
2021-09-06 01:07:49 +00:00
log.Println("Failed to read config file 'config.yml'")
log.Println("Creating default config file...")
c = InitDefaultConfig()
2021-09-06 01:07:49 +00:00
bz, err := yaml.Marshal(c)
if err != nil {
log.Fatal("An error occured while writing the default config file...")
}
2021-09-06 02:48:30 +00:00
err = os.WriteFile(file, bz, 0644)
2021-09-06 01:07:49 +00:00
if err != nil {
log.Fatal("An error occured while writing the default config file...")
}
log.Println("Successfully created the default config file")
} else {
err = yaml.Unmarshal(data, &c)
if err != nil {
log.Fatal("Failed to unmarshal config file 'config.yml', check that its format is correct & try again.", err)
}
log.Println("The file 'config.yml' has been successfully loaded.")
}
return c
}
2021-09-06 01:07:49 +00:00
func InitDefaultConfig() *Config {
server := &ServerCfg{
Host: "127.0.0.1",
Port: 11235,
MaxConns: 2,
Debug: true,
}
db := &DatabaseCfg{
2021-09-09 02:14:06 +00:00
User: "root",
Password: "password",
Host: "127.0.0.1",
Port: 3306,
Name: "habbgo",
2021-09-06 01:07:49 +00:00
}
return &Config{
Server: server,
DB: db,
}
}