Files
janus/internal/config/config.go
T
yangzhaohan 262c8377b9 feat(config): 添加配置管理模块和数据库连接功能
- 实现全局配置结构体,包含服务、数据库和日志配置
- 添加 Viper 配置加载功能,支持 YAML 文件和环境变量
- 创建 config.yaml 配置文件,包含服务器和数据库连接信息
- 集成 GORM 数据库连接功能,支持 PostgreSQL 驱动
- 更新依赖包,添加 postgres 驱动和相关工具库
- 实现 main 入口函数,加载配置并初始化服务
- 创建详细的 Phase 1 基础设施实施计划文档
2026-07-09 08:52:29 +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"`
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)
}
}