package core import ( "fmt" "log/slog" "os" "github.com/joho/godotenv" "github.com/spf13/viper" ) type Configuration struct { Server struct { Port string `yaml:"port"` } `yaml:"server"` Log struct { Path string `json:"path"` Level slog.Level `json:"level"` } `yaml:"log"` DB struct { MongoURI string `yaml:"mongoUri"` DBName string `yaml:"dbName"` } `yaml:"db"` // JWT 配置 JWT struct { SignString string `yaml:"signString"` TimeOut int `yaml:"timeOut"` } `yaml:"jwt"` Viper *viper.Viper `yaml:"-"` } // 初始化配置 func NewConfiguration() (cfg *Configuration, err error) { cfg = &Configuration{} // 加载 .env 文件 err = godotenv.Load() if err != nil { return nil, err } // 读取环境配置 env := os.Getenv("ENV") filename := "" if env == "" { filename = "config/config.yml" } else { filename = fmt.Sprintf("config/config.%v.yml", env) } // 读取配置文件 v := viper.New() // 设置默认值 v.SetDefault("server.port", "8000") v.SetDefault("log.path", "log/app.log") v.SetDefault("log.level", 0) v.SetDefault("jwt.signString", "taotie-api-q2e") v.SetDefault("jwt.timeOut", 3600) v.SetDefault("db.mongoUri", "mongodb://localhost:27017") v.SetDefault("db.dbName", "taotie") // 设置配置文件路径 v.SetConfigFile(filename) // 试着读取文件 err = v.ReadInConfig() if err != nil { return nil, err } err = v.Unmarshal(cfg) if err != nil { return nil, err } cfg.Viper = v return cfg, nil }