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