62 lines
1.4 KiB
Go
62 lines
1.4 KiB
Go
|
|
package config
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"log"
|
||
|
|
|
||
|
|
"gorm.io/driver/mysql"
|
||
|
|
"gorm.io/gorm"
|
||
|
|
"gorm.io/gorm/logger"
|
||
|
|
|
||
|
|
"github.com/spf13/viper"
|
||
|
|
)
|
||
|
|
|
||
|
|
type Config struct {
|
||
|
|
Port string
|
||
|
|
JWTSecret string
|
||
|
|
DatabaseURL string
|
||
|
|
PythonServiceURL string
|
||
|
|
}
|
||
|
|
|
||
|
|
func Load() *Config {
|
||
|
|
viper.SetConfigName("config")
|
||
|
|
viper.SetConfigType("yaml")
|
||
|
|
viper.AddConfigPath("./config")
|
||
|
|
viper.AddConfigPath("../config")
|
||
|
|
viper.AddConfigPath("../../config")
|
||
|
|
|
||
|
|
// 默认值
|
||
|
|
viper.SetDefault("port", "8080")
|
||
|
|
viper.SetDefault("jwt_secret", "your-secret-key-change-in-production")
|
||
|
|
viper.SetDefault("python_service_url", "http://localhost:8081")
|
||
|
|
viper.SetDefault("database_url", "root:root@tcp(localhost:3306)/x_agents?charset=utf8mb4&parseTime=True&loc=Local")
|
||
|
|
|
||
|
|
if err := viper.ReadInConfig(); err != nil {
|
||
|
|
log.Printf("Using default config: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
return &Config{
|
||
|
|
Port: viper.GetString("port"),
|
||
|
|
JWTSecret: viper.GetString("jwt_secret"),
|
||
|
|
DatabaseURL: viper.GetString("database_url"),
|
||
|
|
PythonServiceURL: viper.GetString("python_service_url"),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func InitDB(cfg *Config) (*gorm.DB, error) {
|
||
|
|
dsn := cfg.DatabaseURL
|
||
|
|
if dsn == "" {
|
||
|
|
return nil, fmt.Errorf("database URL is empty")
|
||
|
|
}
|
||
|
|
|
||
|
|
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||
|
|
Logger: logger.Default.LogMode(logger.Info),
|
||
|
|
})
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("failed to connect database: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
log.Println("Database connected successfully")
|
||
|
|
return db, nil
|
||
|
|
}
|