] failed to initialize database, got error failed to connect to `host=localhost ...
🚨 错误信息
🤖 AI解决方案
---
1. 错误翻译
text
原文:failed SASL auth (��������: �û� "postgres" Password ��֤ʧ�� (SQLSTATE 28P01))
译文:SASL 认证失败 (致命错误: 用户 "postgres" 密码验证失败 (SQLSTATE 28P01))
---
2. 原因分析
这是一个 PostgreSQL 数据库连接认证失败 的错误。
postgres 用户的密码不匹配。host=localhost user=postgres database=agi_hub,但缺少或提供了错误的密码。SQLSTATE 28P01 是 PostgreSQL 标准的错误代码,明确指示无效的密码。---
3. 解决方案
通常,您需要在连接字符串中提供正确的密码。以下是修复步骤:
- 如果您忘记了密码,可以在 PostgreSQL 命令行中重置:
``
bash
# 以管理员身份 (如 postgres 用户或系统超级用户) 连接到 PostgreSQL
sudo -u postgres psql
# 在 psql 提示符下,重置 postgres 用户的密码
ALTER USER postgres PASSWORD 'your_secure_password_here';
`
在 Go 代码的连接字符串中提供密码:
- 您原先的连接字符串未指定密码。您需要添加 password` 参数,并通过环境变量管理这个敏感信息(最佳实践)。
go
// 修复后的连接方式(使用环境变量)
import (
"database/sql"
"fmt"
"log"
"os"
_ "github.com/lib/pq" // PostgreSQL驱动
) func main() {
// 从环境变量获取密码,避免硬编码
dbPassword := os.Getenv("DB_PASSWORD")
if dbPassword == "" {
log.Fatal("DB_PASSWORD environment variable is not set")
}
// 构造包含密码的连接字符串
connStr := fmt.Sprintf("host=localhost user=postgres password=%s dbname=agi_hub sslmode=disable", dbPassword)
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatalf("Failed to open database: %v", err)
}
defer db.Close()
// 验证连接
err = db.Ping()
if err != nil {
log.Fatalf("Failed to connect to database: %v", err) // 此处应不再报错
}
log.Println("Successfully connected to database!")
}
在运行程序前,先在终端设置