Files
2026-07-09 17:04:56 +08:00

65 lines
1.3 KiB
Go

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"`
Username string `mapstructure:"username"`
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)
}
}