This commit is contained in:
toom1996
2026-10-18 19:58:37 +08:00
parent 1de1ec46a6
commit 3860e731db
2 changed files with 21 additions and 7 deletions

View File

@ -6,6 +6,8 @@ package config
import (
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"strconv"
@ -80,11 +82,22 @@ type DatabaseConfig struct {
}
// DSN 组装 PostgreSQL 连接串(pgx 驱动,本地开发禁用 SSL)。
//
// 必须用 net/url 对 user/password 做百分号转义:直接 fmt.Sprintf 拼接时,
// 若密码含 @ : / % # ? 等字符,pgx 按 URL 解析会被截断/错解,
// 服务端实际收到的是乱码密码,从而报 28P01(password authentication failed)。
// url.UserPassword 会对这些保留字符正确编码,pgx 再解码还原。
func (d DatabaseConfig) DSN() string {
return fmt.Sprintf(
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
d.User, d.Password, d.Host, d.Port, d.Name,
)
u := url.URL{
Scheme: "postgres",
User: url.UserPassword(d.User, d.Password),
Host: net.JoinHostPort(d.Host, d.Port),
Path: "/" + d.Name,
}
q := u.Query()
q.Set("sslmode", "disable")
u.RawQuery = q.Encode()
return u.String()
}
// Addr 返回 host:port 形式的数据库地址,用于日志展示。