AnCao/pkg/config/config.go
2025-11-05 09:37:29 +08:00

70 lines
1.5 KiB
Go

package config
import (
"fmt"
"os"
"strconv"
)
// DatabaseConfig 数据库配置结构
type DatabaseConfig struct {
Host string
Port int
User string
Password string
DBName string
SSLMode string
}
// GetDatabaseConfig 获取数据库配置
// 优先使用环境变量,如果没有设置则使用默认值
func GetDatabaseConfig() *DatabaseConfig {
// 从环境变量获取配置,如果未设置则使用默认值
host := getEnv("DB_HOST", "pgsql.yuchat.top")
port := getEnvAsInt("DB_PORT", 5432)
user := getEnv("DB_USER", "postgres")
password := getEnv("DB_PASSWORD", "longqi@1314")
dbname := getEnv("DB_NAME", "ankao")
sslmode := getEnv("DB_SSLMODE", "disable")
return &DatabaseConfig{
Host: host,
Port: port,
User: user,
Password: password,
DBName: dbname,
SSLMode: sslmode,
}
}
// getEnv 获取环境变量,如果不存在则返回默认值
func getEnv(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
// getEnvAsInt 获取整型环境变量,如果不存在或转换失败则返回默认值
func getEnvAsInt(key string, defaultValue int) int {
if value := os.Getenv(key); value != "" {
if intValue, err := strconv.Atoi(value); err == nil {
return intValue
}
}
return defaultValue
}
// GetDSN 返回数据库连接字符串
func (c *DatabaseConfig) GetDSN() string {
return fmt.Sprintf(
"host=%s user=%s password=%s dbname=%s port=%d sslmode=%s",
c.Host,
c.User,
c.Password,
c.DBName,
c.Port,
c.SSLMode,
)
}