Files
aiops/backend/internal/config/config.go
T
attacker 7d6674bddd init: EZOps AIOps 智能运维平台
- 前端: React 18 + TypeScript + Vite + Tailwind CSS + shadcn/ui
- 后端: Go + Gin + GORM + JWT (golang-jwt/jwt/v5)
- 功能: 服务器管理、K8s集群、监控告警、CI/CD、自动化运维、审批流程、审计日志
- 文档: 设计文档(ROADMAP/PDD/架构/模块)
2026-06-13 23:09:47 +08:00

97 lines
2.8 KiB
Go

package config
import (
"github.com/spf13/viper"
"go.uber.org/zap"
)
// Config 应用配置
type Config struct {
Mode string `mapstructure:"mode"`
Port string `mapstructure:"port"`
LogLevel string `mapstructure:"log_level"`
Database DatabaseConfig `mapstructure:"database"`
JWT JWTConfig `mapstructure:"jwt"`
Redis RedisConfig `mapstructure:"redis"`
Websocket WebsocketConfig `mapstructure:"websocket"`
}
// DatabaseConfig 数据库配置
type DatabaseConfig struct {
Driver string `mapstructure:"driver"`
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
DBName string `mapstructure:"dbname"`
Charset string `mapstructure:"charset"`
MaxConn int `mapstructure:"max_conn"`
MaxIdle int `mapstructure:"max_idle"`
}
// JWTConfig JWT配置
type JWTConfig struct {
Secret string `mapstructure:"secret"`
ExpireHour int `mapstructure:"expire_hour"`
}
// RedisConfig Redis配置
type RedisConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db"`
}
// WebsocketConfig WebSocket配置
type WebsocketConfig struct {
ReadBufferSize int `mapstructure:"read_buffer_size"`
WriteBufferSize int `mapstructure:"write_buffer_size"`
}
// Load 加载配置
func Load() *Config {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath("./configs")
viper.AddConfigPath(".")
// 设置默认值
viper.SetDefault("mode", "development")
viper.SetDefault("port", "8080")
viper.SetDefault("log_level", "info")
viper.SetDefault("database.driver", "mysql")
viper.SetDefault("database.host", "localhost")
viper.SetDefault("database.port", 3306)
viper.SetDefault("database.charset", "utf8mb4")
viper.SetDefault("database.max_conn", 100)
viper.SetDefault("database.max_idle", 10)
viper.SetDefault("jwt.expire_hour", 24)
viper.SetDefault("redis.host", "localhost")
viper.SetDefault("redis.port", 6379)
viper.SetDefault("websocket.read_buffer_size", 1024)
viper.SetDefault("websocket.write_buffer_size", 1024)
// 读取环境变量
viper.AutomaticEnv()
var cfg Config
if err := viper.ReadInConfig(); err != nil {
zap.L().Warn("config file not found, using defaults", zap.Error(err))
}
if err := viper.Unmarshal(&cfg); err != nil {
zap.L().Fatal("failed to unmarshal config", zap.Error(err))
}
return &cfg
}
// DSN 返回数据库连接字符串
func (d *DatabaseConfig) DSN() string {
if d.Driver == "mysql" {
return d.User + ":" + d.Password + "@tcp(" + d.Host + ":" + string(rune(d.Port)) + ")/" + d.DBName + "?charset=" + d.Charset + "&parseTime=True&loc=Local"
}
return ""
}