93 lines
1.7 KiB
Go
93 lines
1.7 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"io/ioutil"
|
|
"os"
|
|
"path"
|
|
|
|
"git.trj.tw/golang/utils"
|
|
"gopkg.in/yaml.v2"
|
|
)
|
|
|
|
// Database struct
|
|
type Database struct {
|
|
DBName string `yaml:"dbname"`
|
|
Host string `yaml:"host"`
|
|
Port int `yaml:"port"`
|
|
User string `yaml:"user"`
|
|
Pass string `yaml:"pass"`
|
|
SSLCa string `yaml:"ssl_ca"`
|
|
SSLCrt string `yaml:"ssl_crt"`
|
|
SSLKey string `yaml:"ssl_key"`
|
|
SSLMode string `yaml:"ssl_mode"`
|
|
}
|
|
|
|
// Discord struct
|
|
type Discord struct {
|
|
BotToken string `yaml:"bot_token"`
|
|
}
|
|
|
|
// Config -
|
|
type Config struct {
|
|
Port int `yaml:"port"`
|
|
Database *Database `yaml:"database"`
|
|
Discord *Discord `yaml:"discord"`
|
|
}
|
|
|
|
// Errors
|
|
var (
|
|
ErrConfigFileNotFound = errors.New("config file not found")
|
|
)
|
|
|
|
var conf *Config
|
|
|
|
// GetConfig -
|
|
func GetConfig() *Config { return conf }
|
|
|
|
// LoadConfig file
|
|
func LoadConfig(p ...string) (err error) {
|
|
fp := ""
|
|
if len(p) > 0 && len(p[0]) > 0 {
|
|
fp = p[0]
|
|
} else {
|
|
wd, err := os.Getwd()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fp = path.Join(wd, "config.yml")
|
|
}
|
|
|
|
fp = utils.ParsePath(fp)
|
|
|
|
if exists := utils.CheckExists(fp, false); !exists {
|
|
return ErrConfigFileNotFound
|
|
}
|
|
|
|
fileData, err := ioutil.ReadFile(fp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
conf = &Config{}
|
|
|
|
err = yaml.Unmarshal(fileData, conf)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if exists := utils.CheckExists(conf.Database.SSLCa, false); !exists {
|
|
return errors.New("ssl ca file not exists")
|
|
}
|
|
|
|
if exists := utils.CheckExists(conf.Database.SSLCrt, false); !exists {
|
|
return errors.New("ssl crt file not exists")
|
|
}
|
|
|
|
if exists := utils.CheckExists(conf.Database.SSLKey, false); !exists {
|
|
return errors.New("ssl key file not exists")
|
|
}
|
|
|
|
return
|
|
}
|