侧边栏壁纸
博主头像
王旭阳个人博客博主等级

工欲善其事,必先利其器

  • 累计撰写 118 篇文章
  • 累计创建 28 个标签
  • 累计收到 23 条评论

目 录CONTENT

文章目录

Golang加载yaml类型配置文件

wxy
wxy
2022-06-07 / 0 评论 / 5 点赞 / 417 阅读 / 4250 字
温馨提示:
本文最后更新于 2023-08-31,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

通常我们在使用数据库或者其他配置的时候都会有很多敏感信息,如果直接写在代码里会造成信息泄露,而且如果数据库的信息或者其他配置发生变动时,维护起来也很不方便。所以通常情况下使用配置文件的方式。

项目根目录创建config.yml配置文件

wechatHttp:
  #  请求api的验证
  token: 123
  port: 8000
  model: debug
#  model: release

iHttp:
  # post地址
  url: http://127.0.0.1:8090
  authorization: 6r9PEIHcLQoLSn6B512iAiN4fWf4XK36
  # 机器人ID
  robotWxId: wxid_x7t4
  # 主人ID
  masterWxId: wxid_wv
redis:
  host: localhost
  port: 6379
  pwd: 123456
  db: 0

创建config.go读取yml配置

package config

import (
	"fmt"
	"github.com/spf13/viper"
	"os"
)

// Config 保存程序的所有配置信息
var Config = new(AppConfig)

type AppConfig struct {
	*WechatHttp `yaml:"wechatHttp"`
	*IHttp      `yaml:"iHttp"`
	*Redis      `yaml:"redis"`
}
type WechatHttp struct {
	Token string `yaml:"token"`
	Port  string `yaml:"port"`
	Model string `yaml:"model"`
}

type IHttp struct {
	URL           string `yaml:"url"`
	RobotWxId     string `yaml:"robotWxId"`
	MasterWxId    string `yaml:"masterWxId"`
	Authorization string `yaml:"authorization"`
}

type Redis struct {
	Host string `yaml:"host"`
	Port string `yaml:"port"`
	Pwd  string `yaml:"pwd"`
	Db   int    `yaml:"db"`
}

func InitConf() {
	//获取项目的执行路径
	path, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	config := viper.New()
	config.AddConfigPath(path)     //设置读取的文件路径
	config.SetConfigName("config") //设置读取的文件名
	config.SetConfigType("yml")    //设置文件的类型
	err = config.ReadInConfig()
	if err != nil {
		// 处理读取配置文件的错误
		fmt.Printf("viper.ReadInConfig() failed, err:%v\n", err)
		return
	}

	// 配置信息绑定到结构体变量
	err = config.Unmarshal(Config)
	if err != nil {
		fmt.Printf("viper.Unmarshal() failed, err:%v\n", err)
	}
}

在main函数中初始化读取配置

config.InitConf()

package main

import (
	"wechat-http/config"
	"wechat-http/cron"
	"wechat-http/route"
	"wechat-http/util"
	"wechat-http/util/redis"
)

func main() {

	config.InitConf()
	redis.InitRedis()
	cron.InitMyCron()
	util.InitServerInfo()

	r := route.Setup()
	r.Run(":" + config.Config.WechatHttp.Port)

}

5

评论区