You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

75 lines
1.5 KiB

package vConfig
import (
"fmt"
"net/url"
"strings"
)
type Config struct {
Database struct {
DmDsn string `yaml:"dm_dsn"`
} `yaml:"database"`
User string
Pwd string
IP string
Port string
Schema string
}
// LoadConfig 从指定路径加载 YAML 配置
func LoadConfig(envPass string) (*Config, error) {
// 解析 YAML
var config Config
config.Database.DmDsn = envPass
// 预处理:如果字符串以 dm:// 开头则替换为 http:// 便于 url.Parse 解析
u, err := url.Parse(envPass)
if err != nil {
return nil, fmt.Errorf("解析连接字符串失败: %v", err)
}
// 用户信息
userInfo := u.User
if userInfo == nil {
return nil, fmt.Errorf("缺少用户信息")
}
config.User = userInfo.Username()
// 获取密码
if pwd, ok := userInfo.Password(); ok {
config.Pwd = pwd
} else {
return nil, fmt.Errorf("密码解析失败")
}
// 拆分主机和端口
host, port := u.Hostname(), u.Port()
if host == "" {
return nil, fmt.Errorf("缺少IP地址")
}
config.IP = host
// 端口处理(默认端口5236)
if port == "" {
config.Port = "5236" // 达梦默认端口
} else {
config.Port = port
}
// 数据库名(路径部分)
if pathParts := strings.Split(strings.Trim(u.Path, "/"), "/"); len(pathParts) > 0 {
config.Schema = pathParts[0]
} else {
return nil, fmt.Errorf("缺少数据库名")
}
// 获取schema参数
schema := u.Query().Get("schema")
if schema == "" {
return nil, fmt.Errorf("缺少schema参数")
}
config.Schema = schema
return &config, nil
}