gin: vipper解析yaml配置文件
一,安装第三方库
$ go get github.com/spf13/viper
go: downloading github.com/spf13/viper v1.21.0
go: downloading github.com/fsnotify/fsnotify v1.9.0
go: downloading github.com/go-viper/mapstructure/v2 v2.4.0
go: downloading github.com/sagikazarmark/locafero v0.11.0
go: downloading github.com/spf13/afero v1.15.0
go: downloading github.com/spf13/cast v1.10.0
go: downloading github.com/spf13/pflag v1.0.10
go: downloading github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8
go: downloading golang.org/x/text v0.28.0
go: downloading github.com/pelletier/go-toml/v2 v2.2.4
go: downloading go.yaml.in/yaml/v3 v3.0.4
go: added github.com/fsnotify/fsnotify v1.9.0
go: added github.com/go-viper/mapstructure/v2 v2.4.0
go: upgraded github.com/pelletier/go-toml/v2 v2.2.2 => v2.2.4
go: added github.com/sagikazarmark/locafero v0.11.0
go: added github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8
go: added github.com/spf13/afero v1.15.0
go: added github.com/spf13/cast v1.10.0
go: added github.com/spf13/pflag v1.0.10
go: added github.com/spf13/viper v1.21.0
go: added github.com/subosito/gotenv v1.6.0
go: added go.yaml.in/yaml/v3 v3.0.4
go: upgraded golang.org/x/sys v0.20.0 => v0.29.0
go: upgraded golang.org/x/text v0.15.0 => v0.28.0
二,代码:
配置文件:
App:
Port: 8080
Database:
DBType: mysql
UserName: root
Password: rootpassword
Host: 127.0.0.1:3306
DBName: dbname
Charset: utf8
ParseTime: True
MaxIdleConns: 10
MaxOpenConns: 30
库: pkg/setting/setting.go
package setting
import (
"github.com/spf13/viper"
)
type Setting struct {
vp *viper.Viper
}
var sections = make(map[string]interface{})
//读取配置
func NewSetting() (*Setting, error) {
vp := viper.New()
vp.SetConfigName("config")
//vp.AddConfigPath("config")
vp.AddConfigPath(".")
vp.SetConfigType("yaml")
err := vp.ReadInConfig()
if err != nil {
return nil, err
}
s := &Setting{vp}
return s, nil
}
//读取指定的一段
func (s *Setting) ReadSection(k string, v interface{}) error {
err := s.vp.UnmarshalKey(k, v)
if err != nil {
return err
}
if _, ok := sections[k]; !ok {
sections[k] = v
}
return nil
}
//重新加载
func (s *Setting) ReloadAllSection() error {
for k, v := range sections {
err := s.ReadSection(k, v)
if err != nil {
return err
}
}
return nil
}
初始化类:
config/readsettings.go
package config
import (
"fmt"
"mediabank/pkg/setting"
)
//应用配置的struct类型
type AppSettingS struct {
Port string
}
//定义全局变量
var (
AppSetting *AppSettingS
)
//数据库配置的struct类型
type DatabaseSettingS struct {
DBType string
UserName string
Password string
Host string
DBName string
Charset string
ParseTime bool
MaxIdleConns int
MaxOpenConns int
}
//定义全局变量
var (
DatabaseSetting *DatabaseSettingS
)
//读取配置到全局变量
func ReadSettings() error {
s, err := setting.NewSetting()
if err != nil {
return err
}
err = s.ReadSection("App", &AppSetting)
if err != nil {
return err
}
fmt.Println("setting:")
fmt.Println(AppSetting)
err = s.ReadSection("Database", &DatabaseSetting)
if err != nil {
return err
}
fmt.Println("setting:")
fmt.Println(DatabaseSetting)
return nil
}
调用:
package main
import (
"embed"
"fmt"
"log"
"mediabank/config"
"mediabank/global"
"mediabank/routes"
)
// 嵌入文件只能为源码文件同级目录和子目录下的文件
//go:embed static/* templates/*
var embedFs embed.FS
func init() {
//读取配置
err := config.ReadSettings()
if err != nil {
log.Fatalf("init.setupSetting err: %v", err)
}
}
// 入口函数
func main() {
fmt.Println("数据库ip:"+config.DatabaseSetting.Host)
fmt.Println("默认端口:"+config.AppSetting.Port)
//创建访问日志
global.SetupAccessLogger()
//引入路由
r := routes.Routes(embedFs)
//run
err := r.Run(":"+config.AppSetting.Port)
if err != nil {
return
}
}
三,测试效果:
$ go run main.go
setting:
&{8080}
setting:
&{mysql root rootpassword 127.0.0.1:3306 gysy utf8 true 10 30}
数据库ip:127.0.0.1:3306
默认端口:8080
日志文件名:./logs/access20250909.log
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)