package config import ( "fmt" "github.com/gin-gonic/gin" "github.com/spf13/viper" ) // Config 全局配置 type Config struct { Server ServerConfig `mapstructure:"server"` Database DatabaseConfig `mapstructure:"database"` Log LogConfig `mapstructure:"log"` } // ServerConfig 服务基础配置 type ServerConfig struct { Port int `mapstructure:"port"` Mode string `mapstructure:"mode"` } // DatabaseConfig 数据库配置 type DatabaseConfig struct { Host string `mapstructure:"host"` Port int `mapstructure:"port"` User string `mapstructure:"user"` Password string `mapstructure:"password"` DBName string `mapstructure:"dbname"` SSLMode string `mapstructure:"sslmode"` } // LogConfig 日志配置 type LogConfig struct { Level string `mapstructure:"level"` } func Load(path string) (*Config, error) { v := viper.New() v.SetConfigFile(path) v.AutomaticEnv() if err := v.ReadInConfig(); err != nil { return nil, fmt.Errorf("read config: %w", err) } var cfg Config if err := v.Unmarshal(&cfg); err != nil { return nil, fmt.Errorf("unmarshal config: %w", err) } return &cfg, nil } func (c *Config) InitGinMode() { switch c.Server.Mode { case "release": gin.SetMode(gin.ReleaseMode) case "test": gin.SetMode(gin.TestMode) default: gin.SetMode(gin.DebugMode) } }