63 lines
953 B
Go
63 lines
953 B
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"io/ioutil"
|
|
"os"
|
|
"path"
|
|
|
|
"git.trj.tw/golang/utils"
|
|
"github.com/otakukaze/envconfig"
|
|
"gopkg.in/yaml.v2"
|
|
)
|
|
|
|
// Google config
|
|
type Google struct {
|
|
APIKey string `yaml:"api_key" env:"GOOGLE_API_KEY"`
|
|
}
|
|
|
|
// Config main struct
|
|
type Config struct {
|
|
Port int `yaml:"port" env:"PORT"`
|
|
Google Google `yaml:"google"`
|
|
}
|
|
|
|
var conf *Config
|
|
|
|
// Load config from file and env
|
|
func Load(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 !utils.CheckExists(fp, false) {
|
|
return errors.New("config file not found")
|
|
}
|
|
|
|
conf = &Config{}
|
|
|
|
b, err := ioutil.ReadFile(fp)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
err = yaml.Unmarshal(b, conf)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
envconfig.Parse(conf)
|
|
return
|
|
}
|
|
|
|
// Get config struct
|
|
func Get() *Config { return conf }
|