Initial commit

This commit is contained in:
unclesam committed 2026-07-07 16:39:54 +08:00
commit 141baa4e76
45 files changed
+4021

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
package conf
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type Config struct {
Server ServerConfig `mapstructure:"server" yaml:"server"`
Database DatabaseConfig `mapstructure:"database" yaml:"database"`
Logger LoggerConfig `mapstructure:"logger" yaml:"logger"`
}
// LoadConfig 读取并解析配置文件
func LoadConfig(path string) (*Config, error) {
v := viper.New()
v.SetConfigFile(path)
if err := v.ReadInConfig(); err != nil {
return nil, fmt.Errorf("读取配置文件失败: %w", err)
}
var cfg Config
if err := v.Unmarshal(&cfg); err != nil {
return nil, fmt.Errorf("解析配置文件失败: %w", err)
}
// 监听配置变更
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Printf("配置文件已更新: %s\n", e.Name)
})
return &cfg, nil
}
+27
View File
@@ -0,0 +1,27 @@
package conf
import "fmt"
// DatabaseConfig 定义数据库连接配置结构体
type DatabaseConfig struct {
Driver string `mapstructure:"driver" yaml:"driver"`
Host string `mapstructure:"host" yaml:"host"`
Port int `mapstructure:"port" yaml:"port"`
User string `mapstructure:"user" yaml:"user"`
Password string `mapstructure:"password" yaml:"password"`
Dbname string `mapstructure:"dbname" yaml:"dbname"`
}
// Dsn 根据 driver 动态生成 DSN 字符串
func (db DatabaseConfig) Dsn() string {
switch db.Driver {
case "mysql":
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
db.User, db.Password, db.Host, db.Port, db.Dbname)
case "postgres", "postgresql":
return fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
db.Host, db.Port, db.User, db.Password, db.Dbname)
default:
return ""
}
}
+11
View File
@@ -0,0 +1,11 @@
package conf
type LoggerConfig struct {
Prefix string `mapstructure:"prefix" yaml:"prefix"`
Level string `mapstructure:"level" yaml:"level"`
Filename string `mapstructure:"filename" yaml:"filename"`
MaxSize int `mapstructure:"max_size" yaml:"max_size"`
MaxBackups int `mapstructure:"max_backups" yaml:"max_backups"`
MaxAge int `mapstructure:"max_age" yaml:"max_age"`
Compress bool `mapstructure:"compress" yaml:"compress"`
}
+6
View File
@@ -0,0 +1,6 @@
package conf
type ServerConfig struct {
Port int `mapstructure:"port" yaml:"port"`
Mode string `mapstructure:"mode" yaml:"mode"` // debug / release
}