從代碼下面的代碼輸出以下內容: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條經驗 獲得超8個贊
Go 的默認值與 psql 的不同。如果沒有給出主機名,Go 默認使用 localhost,而 psql 默認使用 Unix 域套接字。
要為 Go 指定一個 Unix 域套接字,您需要采取奇怪的方式來讓它通過 URI 驗證:
postgres://postgres:smashthestate@:5432/local?host=%2Ftmp
盡管結尾可能需要更像?host=%2Fvar%2Frun%2Fpostgresql
,具體取決于服務器的配置方式。
但是為什么要指定一個不需要的密碼呢?那會造成毫無意義的混亂。
- 1 回答
- 0 關注
- 110 瀏覽
添加回答
舉報
0/150
提交
取消