go语言读文件 java读文件_GO语言如何读取yaml配置文件

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值