GO语言使用viper管理配置


GO语言使用viper管理配置

1
使用go:embed将同级目录下的conf.yaml一起打包,防止打包可执行文件时找不到conf.yaml的情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package conf

import (
"bytes"
_ "embed"
"github.com/TskFok/ChatAi/app/global"
"github.com/spf13/viper"
)

//go:embed conf.yaml
var conf []byte

func InitConfig() {
viper.SetConfigType("yaml")

err := viper.ReadConfig(bytes.NewReader(conf))

if nil != err {
panic(err)
}

//读取配置文件
global.TlsCert = viper.Get("tls.cert").(string)
global.TlsKey = viper.Get("tls.key").(string)

}