first version, unittest not fin
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"git.trj.tw/golang/utils"
|
||||
"github.com/otakukaze/envconfig"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
// Listen -
|
||||
type Listen struct {
|
||||
TargetHost string `yaml:"target_host"`
|
||||
TargetPort int `yaml:"target_port"`
|
||||
ListenPort int `yaml:"listen_port"`
|
||||
}
|
||||
|
||||
// Config -
|
||||
type Config struct {
|
||||
Verbose int `yaml:"verbose" env:"PROXY_VERBOSE"`
|
||||
Listen []Listen `yaml:"listen"`
|
||||
}
|
||||
|
||||
var conf *Config
|
||||
|
||||
// Load config from file and env
|
||||
func Load(p ...string) (err error) {
|
||||
var fp string
|
||||
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 errors.New("config file not exists")
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadFile(fp)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
conf = &Config{}
|
||||
err = yaml.Unmarshal(b, conf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
envconfig.Parse(conf)
|
||||
return
|
||||
}
|
||||
|
||||
// Get config
|
||||
func Get() *Config { return conf }
|
||||
Reference in New Issue
Block a user