go项目使用配置文件
LYT
首页
分类
标签
项目
留言
友链
关于

go项目使用配置文件

2024年5月17日18时52分
2024年5月17日19时10分
golang
golang
浏览量:
总浏览量:
0

安装viper包

可以使用go语言的第三方包viper来读取配置文件

go get github.com/spf13/viper

建立配置模块

  • 在项目目录下新建一个config文件夹

  • 新建一个config.yml

database: user: root password: liyatai0119 server: port: 2020 wx: key: eakjfbaeifj password: asfnoaubneonwe of
  • 新建一个config.go

在这个go文件中还用了go:embed,可以把配置文件一并打包到二进制文件

package config import ( "bytes" _ "embed" "fmt" "github.com/spf13/viper" ) //go:embed config.yml var configYAML []byte func GetConfig(str string) string { viper.SetConfigType("yaml") if err := viper.ReadConfig(bytes.NewBuffer(configYAML)); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { fmt.Println("找不到配置文件..") } else { fmt.Println("配置文件出错..") } } return viper.GetString(str) }
  • 调用配置文件包 这里使用了gin框架把配置文件的信息展示到浏览器上
package main import ( "viper/config" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/", func(ctx *gin.Context) { ctx.JSON(200, gin.H{ "user": config.GetConfig("database.user"), "password": config.GetConfig("database.password"), "port": config.GetConfig("server.port"), "wxkey": config.GetConfig("wx.key"), "wxpassword": config.GetConfig("wx.password"), }) }) r.Run(":8484") }

运行测试

开发模式运行

编译后运行

go run main.go .\main.exe

我们直接删除配置文件来测试

运行成功!