rpi-vsts-ci-led/pkg/config/config.go

76 lines
1.1 KiB
Go
Raw Normal View History

2020-04-16 09:05:10 +00:00
package config
2020-04-17 08:41:48 +00:00
import (
"errors"
"io/ioutil"
"os"
"path"
"git.trj.tw/golang/utils"
"github.com/jesseduffield/yaml"
"github.com/otakukaze/envconfig"
)
2020-04-16 09:05:10 +00:00
type Server struct {
Port int `yaml:"port" env:"SERVER_PORT"`
}
2020-04-17 08:41:48 +00:00
type Remote struct {
WSLoc string `yaml:"ws_loc" env:"REMOTE_WS_LOC"`
}
type LED struct {
Count int `yaml:"count" env:"LED_COUNT"`
Pin int `yaml:"pin" env:"LED_PIN"`
}
2020-04-16 09:05:10 +00:00
type Config struct {
Server Server `yaml:"server"`
2020-04-17 08:41:48 +00:00
Remote Remote `yaml:"remote"`
LED LED `yaml:"led"`
2020-04-16 09:05:10 +00:00
}
var c *Config
func Load(p ...string) error {
2020-04-17 08:41:48 +00:00
var fp string
if len(p) > 0 && p[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")
}
// read config file
b, err := ioutil.ReadFile(fp)
if err != nil {
return err
}
c = &Config{}
if err := yaml.Unmarshal(b, c); err != nil {
return err
}
envconfig.Parse(c)
2020-04-16 09:05:10 +00:00
return nil
}
2020-04-17 08:41:48 +00:00
func Get() *Config {
if c == nil {
panic(errors.New("config not init"))
}
return c
}