1.介绍
Viper是Go应用程序的完整配置解决方案,包括12因素应用程序。它旨在应用程序中工作,并且可以处理所有类型的配置需求和格式。它支持:
- 设置默认值
- 从 JSON、TOML、YAML、HCL、envfile 和 Java 属性配置文件读取
- 实时观看和重新读取配置文件(可选)
- 从环境变量读取
- 从远程配置系统(etcd或Consul)读取,并观察更改
- 从命令行标志读取
- 从缓冲区读取
- 设置显式值
Viper 可以被视为满足所有应用程序配置需求的注册表。
具体参考https://github.com/spf13/viper
实践
config\application.yaml
server:
port: 8080
datasource:
driverName: mysql
host: 127.0.0.1
port: 3306
database: liuyunshengsir
username: root
password: 123456
charset: utf8
loc: Asia/Shanghai
获取
package main
import (
"fmt"
"liuyunshengsir/lys_meet/controller1"
"liuyunshengsir/lys_meet/docs"
"os"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
func main() {
InitConfig()
// programmatically set swagger info
docs.SwaggerInfo.Title = "Swagger Example API-刘云生sir"
docs.SwaggerInfo.Description = "This is a test server."
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Host = "127.0.0.1:8080/"
//docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r := gin.New()
v1 := r.Group("/api/v1")
{
v1.GET("/GetConfig", GetConfig)
}
// use ginSwagger middleware to serve the API docs
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
}
/**
初始化配置文件
*/
func InitConfig() {
workDir, _ := os.Getwd()
viper.SetConfigName("application")
viper.SetConfigType("yaml")
viper.AddConfigPath(workDir + "/config")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
}
// @sayHello
// @Description GetConfig
// @Router /api/v1/GetConfig [get]
func GetConfig(c *gin.Context) {
driverName := viper.GetString("datasource.driverName")
c.JSON(200, gin.H{
"describe": "配置文件数据库返回的参数",
"name": driverName,
})
}