conf.go 1.1 KB
Newer Older
E
eoLinker API Management 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package conf

import (
	"io/ioutil"
	"os"

	"gopkg.in/yaml.v2"
)

var (
	_Configure map[string]string
	lastFile   = ""
)

Y
Your Name 已提交
15
//Get get
E
eoLinker API Management 已提交
16 17 18 19
func Get(name string) (string, bool) {
	v, has := _Configure[name]
	return v, has
}
Y
Your Name 已提交
20 21

//Set set
E
eoLinker API Management 已提交
22 23 24 25
func Set(name, value string) {
	_Configure[name] = value
}

Y
Your Name 已提交
26
//Value value
E
eoLinker API Management 已提交
27 28 29
func Value(name string) string {
	return _Configure[name]
}
Y
Your Name 已提交
30 31

//Reload reload
E
eoLinker API Management 已提交
32 33 34
func Reload() {
	ReadConfigure(lastFile)
}
Y
Your Name 已提交
35 36

//MastValue mastValue
E
eoLinker API Management 已提交
37 38 39 40 41 42 43
func MastValue(name string, def string) string {
	v, h := _Configure[name]
	if h {
		return v
	}
	return def
}
Y
Your Name 已提交
44 45

//ReadConfigure 读取配置
E
eoLinker API Management 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
func ReadConfigure(filepath string) error {
	file, err := os.Open(filepath)
	if err != nil {
		return err
	}
	content, err := ioutil.ReadAll(file)
	if err != nil {
		return err
	}
	configure := make(map[string]string)
	err = yaml.Unmarshal(content, &configure)
	if err != nil {
		return err
	}
	_Configure = configure
	lastFile = filepath
	return nil
}

Y
Your Name 已提交
65
//Save 更新配置文件
E
eoLinker API Management 已提交
66 67 68 69 70 71 72 73 74
func Save() (bool, error) {
	confStr, err := yaml.Marshal(_Configure)
	if err != nil {
		return false, err
	}

	ioutil.WriteFile(lastFile, confStr, 0666)
	return true, nil
}