Golang使用第三方包viper读取yaml配置信息

Golang有很多第三方包,其中的 viper 支持读取多种配置文件信息。本文只是做一个小小demo,用来学习入门用的。

1、安装

  go get github.com/spf13/viper

2、编写一个yaml的配置文件,config.yaml

database:
  host: 127.0.0.1
  user: root
  dbname: test
  pwd: 123456
  

3、编写学习脚本main.go,读取config.yaml配置信息

package main

import (
	"fmt"
	"os"

	"github.com/spf13/viper"
)

func main() {
	//获取项目的执行路径
	path, err := os.Getwd()
	if err != nil {
		panic(err)
	}

	config := viper.New()

	config.AddConfigPath(path)     //设置读取的文件路径
	config.SetConfigName("config") //设置读取的文件名
	config.SetConfigType("yaml")   //设置文件的类型
	//尝试进行配置读取
	if err := config.ReadInConfig(); err != nil {
		panic(err)
	}

	//打印文件读取出来的内容:
	fmt.Println(config.Get("database.host"))
	fmt.Println(config.Get("database.user"))
	fmt.Println(config.Get("database.dbname"))
	fmt.Println(config.Get("database.pwd"))

}

4、执行go run main.go

输出:

127.0.0.1
root
test
123456

ok!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值