f7f92c9853
- 配置文件和SQLite数据库存储在/app/data - Docker volume持久化数据 - 无需预设环境变量,安装向导自动配置
89 lines
2.0 KiB
Go
89 lines
2.0 KiB
Go
package config
|
|
|
|
import (
|
|
"log"
|
|
"os"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
var dataDir = "/app/data"
|
|
|
|
func Init() {
|
|
if dir := os.Getenv("DATA_DIR"); dir != "" {
|
|
dataDir = dir
|
|
}
|
|
if _, err := os.Stat(dataDir); os.IsNotExist(err) {
|
|
os.MkdirAll(dataDir, 0755)
|
|
}
|
|
|
|
viper.SetConfigName("config")
|
|
viper.SetConfigType("yaml")
|
|
viper.AddConfigPath(dataDir)
|
|
viper.AddConfigPath(".")
|
|
viper.AddConfigPath("./config")
|
|
|
|
setDefaults()
|
|
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
log.Printf("Warning: Config file not found, using defaults: %v", err)
|
|
}
|
|
|
|
viper.AutomaticEnv()
|
|
}
|
|
|
|
func GetDataDir() string {
|
|
return dataDir
|
|
}
|
|
|
|
// setDefaults 设置默认配置值
|
|
func setDefaults() {
|
|
// 应用配置
|
|
viper.SetDefault("app.name", "verification-platform")
|
|
viper.SetDefault("app.env", "development")
|
|
viper.SetDefault("app.port", "8080")
|
|
viper.SetDefault("app.jwt_secret", "your-secret-key")
|
|
viper.SetDefault("app.jwt_expire", "24h")
|
|
|
|
// 数据库配置
|
|
viper.SetDefault("database.type", "auto")
|
|
viper.SetDefault("database.host", "localhost")
|
|
viper.SetDefault("database.port", "3306")
|
|
viper.SetDefault("database.name", "verification_platform")
|
|
viper.SetDefault("database.username", "root")
|
|
viper.SetDefault("database.password", "")
|
|
viper.SetDefault("database.charset", "utf8mb4")
|
|
viper.SetDefault("database.max_idle_conns", "10")
|
|
viper.SetDefault("database.max_open_conns", "100")
|
|
|
|
// Redis配置
|
|
viper.SetDefault("redis.host", "localhost")
|
|
viper.SetDefault("redis.port", "6379")
|
|
viper.SetDefault("redis.password", "")
|
|
viper.SetDefault("redis.db", "0")
|
|
|
|
// 日志配置
|
|
viper.SetDefault("log.level", "info")
|
|
viper.SetDefault("log.format", "json")
|
|
}
|
|
|
|
// GetString 获取字符串配置
|
|
func GetString(key string) string {
|
|
return viper.GetString(key)
|
|
}
|
|
|
|
// GetInt 获取整数配置
|
|
func GetInt(key string) int {
|
|
return viper.GetInt(key)
|
|
}
|
|
|
|
// GetBool 获取布尔配置
|
|
func GetBool(key string) bool {
|
|
return viper.GetBool(key)
|
|
}
|
|
|
|
// GetStringSlice 获取字符串切片配置
|
|
func GetStringSlice(key string) []string {
|
|
return viper.GetStringSlice(key)
|
|
}
|