From code
The code bellow outputs the following:
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...
}
From terminal
However, connection to db is possible from terminal. For example, this command if run with the same parameters (db name, user name, password) will give correct output:
psql -d local -U postgres -W -c 'select * from interest;'
Notes
- Command works correctly even if sent by user that is neither
root
norpostgres
. - Authentication method for local connection is set to
trust
insidepg_hba.conf
:
local all all trust
So, what am I missing here? Why everything works fine from the command line but doesn't work from code?
CodePudding user response:
Go's defaults are different from psql's. If no hostname is given, Go defaults to using localhost, while psql defaults to using the Unix domain sockets.
To specify a Unix domain socket to Go, you need to do it oddly to get it to survive URI validation:
postgres://postgres:smashthestate@:5432/local?host=/tmp
Though the end might need to be more like ?host=/var/run/postgresql
, depending on how the server was configured.
But why are you specifying a password which is not needed? That is going to cause pointless confusion.