无法使用 pgx 驱动程序连接到 PostgreSQL 数据库,但可以使用终端

从代码

下面的代码输出以下内容:


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 1


import (

    "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;'


笔记

  1. 即使用户发送的命令既不是 也可以正常root工作postgres

  2. 本地连接的身份验证方法设置为trustinside pg_hba.conf

local   all             all                                     trust

那么,我在这里错过了什么?为什么在命令行中一切正常,但在代码中却不行?


拉丁的传说
浏览 59回答 1
1回答

慕田峪9158850

Go 的默认值与 psql 的不同。如果没有给出主机名,Go 默认使用 localhost,而 psql 默认使用 Unix 域套接字。要为 Go 指定一个 Unix 域套接字,您需要采取奇怪的方式来让它通过 URI 验证:postgres://postgres:smashthestate@:5432/local?host=%2Ftmp尽管结尾可能需要更像?host=%2Fvar%2Frun%2Fpostgresql,具体取决于服务器的配置方式。但是为什么要指定一个不需要的密码呢?那会造成毫无意义的混乱。
打开App,查看更多内容
随时随地看视频慕课网APP