dorisbot/pkg/config/config.go

78 lines
1.2 KiB
Go
Raw Normal View History

2019-06-28 09:37:37 +00:00
package config
import (
"errors"
"io/ioutil"
"os"
"path"
"git.trj.tw/golang/utils"
"gopkg.in/yaml.v2"
)
// Database struct
type Database struct {
2019-07-02 10:05:26 +00:00
DBName string `yaml:"dbname"`
Host string `yaml:"host"`
Port int `yaml:"port"`
User string `yaml:"user"`
Pass string `yaml:"pass"`
2019-06-28 09:37:37 +00:00
}
// Discord struct
type Discord struct {
BotToken string `yaml:"bot_token"`
}
// Config -
type Config struct {
Port int `yaml:"port"`
2019-09-16 09:16:58 +00:00
SelfKey string `yaml:"self_key"`
2019-06-28 09:37:37 +00:00
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
}
return
}