从代码下面的代码输出以下内容:2022/06/21 16:01:07 Failed to connect to db: failed to connect to 'host=localhost user=postgres database=local': server error (FATAL: Ident authentication failed for user "postgres" (SQLSTATE 28000)) exit status 1import ( "context" "log" "github.com/jackc/pgx/v4")func main() { dbCtx := context.Background() db, err := pgx.Connect( dbCtx, "postgres://postgres:smashthestate@localhost:5432/local", ) if err != nil { log.Fatalf("Failed to connect to db: %v\n", err) } defer db.Close(dbCtx) // do stuff with db...}从终端但是,可以从终端连接到数据库。例如,如果使用相同的参数(数据库名称、用户名、密码)运行此命令,将给出正确的输出:psql -d local -U postgres -W -c 'select * from interest;'笔记即使用户发送的命令既不是 也可以正常root工作postgres。本地连接的身份验证方法设置为trustinside pg_hba.conf:local all all trust那么,我在这里错过了什么?为什么在命令行中一切正常,但在代码中却不行?
1 回答
慕田峪9158850
TA贡献1794条经验 获得超7个赞
Go 的默认值与 psql 的不同。如果没有给出主机名,Go 默认使用 localhost,而 psql 默认使用 Unix 域套接字。
要为 Go 指定一个 Unix 域套接字,您需要采取奇怪的方式来让它通过 URI 验证:
postgres://postgres:smashthestate@:5432/local?host=%2Ftmp
尽管结尾可能需要更像?host=%2Fvar%2Frun%2Fpostgresql
,具体取决于服务器的配置方式。
但是为什么要指定一个不需要的密码呢?那会造成毫无意义的混乱。
- 1 回答
- 0 关注
- 58 浏览
添加回答
举报
0/150
提交
取消