user viper

This commit is contained in:
张超
2025-04-15 16:47:00 +08:00
parent 33cb413a12
commit f52d5a698b
12 changed files with 329 additions and 214 deletions

View File

@@ -1,23 +0,0 @@
[mysql]
Type = mysql
Host = 47.93.160.42
Port = 3630
User = blog
Password = qI7=bL4@iJ
DBName = blog
Charset = utf8mb4
Prefix = gin_
;Prefix = gin_
[jwt]
SecretKey = \x13\xbf\xd2 1\xce\x8b\xc1\t\xc1=\xec\x07\x93\xd4\x9e\xbco\xb0Z
[project]
StaticUrlMapPath = {"assets/static/": "static/", "assets/docs/": "docs/", "media/": "media/"}
TemplateGlob = templates/**/*
MediaFilePath = "media/upload/"
[server]
Port = 7890
ReadTimeout = 60
WriteTimeout = 60

View File

@@ -8,16 +8,13 @@ package config
import (
"fmt"
"log"
"time"
"github.com/fsnotify/fsnotify"
"github.com/go-ini/ini"
"github.com/spf13/viper"
)
type SqlDataBase struct {
Type string
type DataBaseConfig struct {
Host string
Port string
User string
@@ -25,6 +22,9 @@ type SqlDataBase struct {
DBName string
Charset string
Prefix string
Driver string
DSN string
MaxConns int `mapstructure:"max_conns"`
}
type Jwt struct {
@@ -32,75 +32,95 @@ type Jwt struct {
}
type Project struct {
StaticUrlMapPath string
StaticUrlMapPath []interface{}
TemplateGlob string
MediaFilePath string
CurrentTheme string
}
type Server struct {
type ServerConfig struct {
Port string
EnableGzip bool `mapstructure:"enable_gzip"`
CSRFSecret string `mapstructure:"csrf_secret"`
ReadTimeout time.Duration
WriteTimeout time.Duration
}
var (
DataBase = &SqlDataBase{}
JwtSecretKey = &Jwt{}
ProjectCfg = &Project{}
HttpServer = &Server{}
)
func SetUp() {
cfg, err := ini.Load("config/conf.ini")
if err != nil {
panic(err)
}
if err := cfg.Section("mysql").MapTo(DataBase); err != nil {
panic(err)
}
if err := cfg.Section("jwt").MapTo(JwtSecretKey); err != nil {
panic(err)
}
if err := cfg.Section("project").MapTo(ProjectCfg); err != nil {
panic(err)
}
if err := cfg.Section("server").MapTo(HttpServer); err != nil {
panic(err)
}
type ThemeConfig struct {
Current string
AllowUpload bool `mapstructure:"allow_upload"`
}
type SecurityConfig struct {
JWTSecret string `mapstructure:"jwt_secret"`
CORSAllowedOrigins []string `mapstructure:"cors_allowed_origins"`
}
type Config struct {
Env string
Server ServerConfig
DataBase DataBaseConfig
Theme ThemeConfig
JwtSecretKey Jwt
Project Project
Security SecurityConfig
}
func SetUp1() {
func LoadConfig(configPath string) (*Config, error) {
// 1. 基础配置
viper.SetConfigFile(configPath)
// 设置配置文件的名称(不包括扩展名)
viper.SetConfigName("config.yml")
viper.SetConfigName("config")
// 设置配置文件所在的目录
viper.AddConfigPath("./conf")
viper.AddConfigPath("./config")
// 设置配置文件的类型为YAML
viper.SetConfigType("yaml")
// 3. 自动读取环境变量(自动转换大写和下划线)
viper.AutomaticEnv()
viper.SetEnvPrefix("BLOG") // 环境变量前缀 BLOG_xxx
// 2. 设置默认值
viper.SetDefault("server.port", 3000)
viper.SetDefault("database.max_conns", 10)
viper.SetDefault("theme.allow_upload", false)
// 读取配置文件
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading config file, %s", err)
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
return nil, fmt.Errorf("配置文件未找到: %s", configPath)
}
return nil, fmt.Errorf("读取配置文件失败: %w", err)
}
//监控并重新读取配置文件
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
// 配置文件发生变更之后会调用的回调函数
fmt.Println("Config file changed:", e.Name)
})
// 5. 反序列化到结构体
var cfg Config
if err := viper.Unmarshal(&cfg); err != nil {
return nil, fmt.Errorf("配置解析失败: %w", err)
}
// 6. 校验必要配置项
// if cfg.Security.JWTSecret == "" {
// return nil, fmt.Errorf("安全配置错误: jwt_secret 必须设置")
// }
// 获取配置值
mysqlHost := viper.GetString("mysql.Host")
mysqlHost := viper.GetString("database.Host")
jwtSecretKey := viper.GetString("jwt.SecretKey")
serverPort := viper.GetInt("server.Port")
templateGlob := viper.GetString("project.TemplateGlob")
// 打印获取到的配置值
fmt.Printf("MySQL Host: %s\n", mysqlHost)
fmt.Printf("JWT Secret Key: %s\n", jwtSecretKey)
fmt.Printf("Server Port: %d\n", serverPort)
fmt.Printf("TemplateGlob: %s\n", templateGlob)
return &cfg, nil
}
func GetCurrentTheme() string {
return "default"

View File

@@ -1,5 +1,5 @@
database:
Type: mysql
Driver: mysql
Host: 47.93.160.42
Port: 3630
User: blog
@@ -7,10 +7,13 @@ database:
DBName: blog
Charset: utf8mb4
Prefix: gin_
DSN: "mysql:mysql@tcp(47.93.160.42:3630)/gin_blog?charset=utf8mb4&parseTime=True&loc=Local"
# Prefix: gin_ # This line is commented out in the original .ini file
jwt:
SecretKey: "\x13\xbf\xd2 1\xce\x8b\xc1\t\xc1=\xec\x07\x93\xd4\x9e\xbco\xb0Z"
security:
JWTSecret: "jwt_secret"
project:
StaticUrlMapPath:
@@ -21,7 +24,7 @@ project:
MediaFilePath: "media/upload/"
server:
Port: 7890
Port: 8090
ReadTimeout: 60
WriteTimeout: 60