package config import ( "fmt" "os" "path/filepath" "strings" "time" "github.com/spf13/viper" ) var ( conf *Config ) func InitConfig() error { // 加载配置 err := readConfigFile() if err != nil { return fmt.Errorf("read config file failed: %w", err) } initLogger() initUniqueId() return nil } func defaultConfig() *Config { return &Config{ Server: ServerConfig{ Port: "8080", BaseUrl: "/", WsUrl: "/ws", }, JWT: JwtConfig{ Secret: "qwemwddlalmskadklsdklamlkdsakld", AccessExpiry: 24 * time.Hour, }, UniqueID: UniqueIDConfig{ DataCenterID: 1, WorkerID: 1, }, Postgres: PostgresConfig{ Port: 5432, SslMode: false, TimeZone: "Asia/Shanghai", MaxOpenConns: 20, MaxIdleConns: 10, ConnMaxLifetime: 30 * time.Minute, }, Log: LogConfig{ Level: "info", Dir: "logs", MaxSize: 100, MaxBackups: 10, MaxAge: 30, Compress: true, }, } } func readConfigFile() error { // 配置文件的目录 prefix := "resources" env := GetEnv() // 获取当前环境 // 设置默认值 conf = defaultConfig() // 先给默认结构体 // 默认配置文件 confFileRelPath := filepath.Join(prefix, "application.yaml") // 创建 viper 实例 v := viper.New() // 首先加载默认的 application.yaml v.SetConfigFile(confFileRelPath) v.SetConfigType("yaml") // 读取默认配置文件 if err := v.ReadInConfig(); err != nil { panic(err) } // 根据环境加载不同的配置文件 switch env { case "dev": v.SetConfigFile(filepath.Join(prefix, "application-dev.yaml")) case "build": v.SetConfigFile(filepath.Join(prefix, "application-build.yaml")) } // 如果需要,合并环境特定的配置文件 if err := v.MergeInConfig(); err != nil { return fmt.Errorf("merge env config failed: %w", err) } if err := v.Unmarshal(conf); err != nil { return fmt.Errorf("unmarshal config failed: %w", err) } fmt.Println("✅️ 加载配置成功") // 设置环境变量 conf.Env = env return nil } // GetEnv 获取 GO_ENV 环境变量,默认返回 "dev" func GetEnv() string { e := os.Getenv("GO_ENV") if len(e) == 0 { // 如果没有设置 GO_ENV,使用默认的 "dev" 配置 return "dev" } return e } // GetConf 获取配置信息 func GetConf() *Config { return conf } // GetServerPort 项目启动端口 func GetServerPort() string { port := conf.Server.Port if strings.HasPrefix(port, ":") { return port } return ":" + port }