1.解析yaml属性文件
引入第三库
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
)
定义解析对象
//总配置
type Cfg struct {
Name string `yaml:name`
Auto bool `yaml:auto`
Port int `yaml:port`
Blackip []string
Clusterip []string
Health Health
}
type Health struct {
Url string
Cmd string
Interval string
Timeout string
Disable bool
}
解析处理
//定义从配置文件转换成的对象
var ConfigInfo Cfg
//定义解析后的配置文件路径
var activePath string
func InitActivePath(relativePath, activeEnv string) {
if len(activeEnv) <= 0 {
activeEnv = DefaultDevelopmentEnv
}
activePath = relativePath + "/application_" + activeEnv + ".yaml"
}
// 1.从配置文件中加载配置
func InitCommConfig(relativePath string,activeEnv string) error {
InitActivePath(relativePath,activeEnv)
//根据路径读文件内容
content, err := ioutil.ReadFile(activePath)
if err != nil {
fmt.Println(err.Error())
os.Exit(-1)
}
//yaml解析,并赋值给ConfigInfo
err = yaml.Unmarshal(content, &ConfigInfo)
fmt.Print(ConfigInfo)
return err
}
2. yaml文件示例
name: testsvr
blackip:
- 1.1.1.1
- 2.2.2.2
auto: false
port: 9999
clusterip: [3.3.3.3,4.4.4.4]
health:
url: http://localhost:5444 # 地址
cmd: netstat -anlt # 命令
interval: 3s # 间隔时间
timeout: 20s # 超时时间
disable: true # 是否启用
3.启动时初始化
config.InitCommConfig("./resource","dev")
示例:https://gitee.com/xinihuhu/gin-gorm