Go编程之读取yml文件

一、下载依赖

go get -u gopkg.in/yaml.v2

二、创建yml配置文件

# 相关配置
server:
  # 端口
  part: 8888
  # banner 配置
  banner:
    # banner 文件的名字
    name: banner.txt
    # 是否加载
    loading: true
# 数据库相关配置
data:
  # 数据类型
  data-type: mysql
  # 数据库名称
  database: test
  # 链接
  url: 'www.baidu.com'
  # 用户名
  username: long
  # 密码
  password: 123456
  # 初始化SQL配置
  init:
    name: init.sql
    status: true
  # 测试数据SQL配置
  test:
    name: test.sql
    status: false

三、创建结构体

type Config struct {
	// 服务器相关配置
	Server struct{
		Part string `yml:"part"`
		Banner struct{
			Name string `yml:"name"`
			Loading bool `yml:"loading"`
		} `yml:"banner"`
	} `yml:"server"`
	// 数据库相关配置
	Data struct{
		DataType string `yml:"data-type"`
		DataBase string `yml:"database"`
		Url string `yml:"url"`
		Username string `yml:"username"`
		Password string `yml:"password"`
		Init struct{
			Name string `yml:"name"`
			Status bool `yml:"status"`
		} `yml:"init"`
		Test struct{
			Name string `yml:"name"`
			Status bool `yml:"status"`
		} `yml:"test"`
	} `yml:"data"`
}

四、读取工具

func NewConfig() *Config {
	return &Config{}
}


func (config *Config) ReadConfig() {
	file, err := ioutil.ReadFile("config/config.yml")
	if err != nil {
		log.Fatalln("读取文件config.yml发生错误")
		return
	}
	if yaml.Unmarshal(file, config) != nil {
		log.Fatalln("解析文件config.yml发生错误")
		return
	}
	fmt.Println(config)
}

五、使用

import (
	"fmt"
	"gin-web/config"
)

func init() {
	config.NewConfig().ReadConfig()
}

func main() {
	fmt.Println("Gin-Web,启动")
}

读取结果&{{8888 {banner.txt true}} { test www.baidu.com long 123456 {init.sql true} {test.sql false}}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值