yaml文件读取

本文介绍了在Go语言中使用YAML.v2和Viper库来解析和读取配置文件的方法,包括如何定义结构体和从文件中提取`host`,`port`,`username`,`password`,和`MaxSize`等关键信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

准备数据

app:
  host: 127.0.0.1
  port: 3306
  username: root
  password: root
path:
  suffix: bucket
  maxSize: 100

方式一、yaml.v2

package main

import (
	"log"
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

type App struct {
	Host     string `yaml:"host" json:"host"`
	Port     int    `yaml:"port" json:"port"`
	Username string `yaml:"username" json:"username"`
	Password string `yaml:"password" json:"password"`
}

type Path struct {
	Suffix  string `yaml:"suffix" json:"suffix"`
	MaxSize int    `yaml:"maxSize" json:"maxsize"`
}

type Config struct {
	App  App  `yaml:"app" json:"app"`
	Path Path `yaml:"log" json:"log"`
}

func main() {
	//通过ioutil导入配置文件
	file, err := ioutil.ReadFile("./config.yml")
	if err != nil {
		log.Println(err.Error())
	}
	config := new(Config)
	//将配置文件读取到结构体中
	err = yaml.Unmarshal(file, &config)
	if err != nil {
		log.Println(err.Error())
	}
	username := config.App.Username
	log.Println("username:" + username)
	log.Println("MaxSize: ", config.Path.MaxSize)

}

方式二、Viper

1.viper支持的格式:JSON、TOML、YAML、HCL、Java properties、INI。

2.viper可以热加载配置文件。

3.使用

package main

import (
	"log"

	"github.com/spf13/viper"
)

type App struct {
	Host     string `yaml:"host" json:"host"`
	Port     int    `yaml:"port" json:"port"`
	Username string `yaml:"username" json:"username"`
	Password string `yaml:"password" json:"password"`
}

type Path struct {
	Suffix  string `yaml:"suffix" json:"suffix"`
	MaxSize int    `yaml:"maxSize" json:"maxsize"`
}

type Config struct {
	App  App  `yaml:"app" json:"app"`
	Path Path `yaml:"log" json:"log"`
}

func main() {
	//设置配置文件类型
	viper.SetConfigType("yaml")
	//导入配置文件
	viper.SetConfigFile("./config.yml")
	//读取配置文件
	err := viper.ReadInConfig()
	if err != nil {
		log.Println(err.Error())
	}
	var config *Config
	//将配置文件读到结构体中
	err = viper.Unmarshal(&config)
	if err != nil {
		log.Println(err.Error())
	}
	username := config.App.Username
	log.Println("username:" + username)
	log.Println("MaxSize: ", config.Path.MaxSize)
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值