first
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
|
||||
"git.trj.tw/golang/utils"
|
||||
yaml "gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
// Config -
|
||||
type Config struct {
|
||||
Port int `yaml:"port"`
|
||||
AWS struct {
|
||||
SharedConfig bool `yaml:"shared_config"`
|
||||
AccessKey string `yaml:"access_key"`
|
||||
SecretKey string `yaml:"secret_key"`
|
||||
} `yaml:"aws"`
|
||||
}
|
||||
|
||||
var conf *Config
|
||||
|
||||
// LoadConfig -
|
||||
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 errors.New("config file not exists")
|
||||
}
|
||||
data, err := ioutil.ReadFile(fp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
conf = &Config{}
|
||||
err = yaml.Unmarshal(data, conf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
envOverride()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func envOverride() {
|
||||
var str string
|
||||
// set port
|
||||
str = os.Getenv("PORT")
|
||||
if len(str) > 0 {
|
||||
num, err := strconv.Atoi(str)
|
||||
if err == nil && num > 0 && num < 65536 {
|
||||
conf.Port = num
|
||||
}
|
||||
}
|
||||
|
||||
// set aws use shared config
|
||||
str = os.Getenv("AWS_SHARED_CONF")
|
||||
if len(str) > 0 {
|
||||
if str == "1" {
|
||||
conf.AWS.SharedConfig = true
|
||||
} else if str == "0" {
|
||||
conf.AWS.SharedConfig = false
|
||||
}
|
||||
}
|
||||
|
||||
// set aws access key
|
||||
str = os.Getenv("AWS_ACCESS_KEY")
|
||||
if len(str) > 0 {
|
||||
conf.AWS.AccessKey = str
|
||||
}
|
||||
|
||||
// set aws secret key
|
||||
str = os.Getenv("AWS_SECRET_KEY")
|
||||
if len(str) > 0 {
|
||||
conf.AWS.SecretKey = str
|
||||
}
|
||||
}
|
||||
|
||||
// GetConfig -
|
||||
func GetConfig() *Config {
|
||||
return conf
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package option
|
||||
|
||||
import "flag"
|
||||
|
||||
// Options -
|
||||
type Options struct {
|
||||
Help bool
|
||||
Config string
|
||||
}
|
||||
|
||||
var opts *Options
|
||||
|
||||
// RegOptions -
|
||||
func RegOptions() {
|
||||
opts = &Options{}
|
||||
flag.StringVar(&opts.Config, "config", "", "config file path - default: `pwd/config.yml`")
|
||||
flag.StringVar(&opts.Config, "f", "", "config file path - default: `pwd/config.yml`")
|
||||
flag.BoolVar(&opts.Help, "help", false, "show help")
|
||||
flag.Parse()
|
||||
}
|
||||
|
||||
// GetOptions -
|
||||
func GetOptions() *Options { return opts }
|
||||
Reference in New Issue
Block a user