可以使用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
在这个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) }
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
我们直接删除配置文件来测试
运行成功!