Sławosz
Sławosz

Reputation: 11697

Golang lib/pg can't connect to postgres

I have such code:

package main

import (
        "database/sql"
        "fmt"
        "log"

        _ "github.com/lib/pq"
)

func main() {
        db, err := sql.Open("postgres", "user=postgres dbname=vagrant sslmode=disable")
        if err != nil {
                log.Fatal(err)
        }

        rows, err := db.Query("SELECT 3+5")
        if err != nil {
                log.Fatal(err)
        }
        fmt.Println(rows)
}

And its result is:

[vagrant@localhost go-postgres]$ go run test.go
2015/12/19 11:03:53 pq: Ident authentication failed for user "postgres"
exit status 1

But I can access postgres:

[vagrant@localhost go-postgres]$ psql -U postgres vagrant
psql (9.4.4)
Type "help" for help.

vagrant=#

And I don't have any troubles with using Rails app with postgres.

Anyone has an idea?

EDIT: Here is my pg_hba.conf:

local   all             all                                     trust
host    all             all             127.0.0.1/32            ident
host    all             all             ::1/128                 ident

EDIT2:

I found this in my postgres logs:

< 2015-12-19 12:13:05.094 UTC >LOG:  could not connect to Ident server at address "::1", port 113: Connection refused
< 2015-12-19 12:13:05.094 UTC >FATAL:  Ident authentication failed for user "postgres"
< 2015-12-19 12:13:05.094 UTC >DETAIL:  Connection matched pg_hba.conf line 84: "host    all             all             ::1/128                 ident"

I think it will really help ;)

Upvotes: 3

Views: 9154

Answers (3)

Shiva
Shiva

Reputation: 2838

For me, setting host to /run/postgresql worked.
Credit: https://github.com/lib/pq/issues/645#issuecomment-320799610

The host url depends on the socket Postgres is using. The socket location varies based on how and where postgres was built. The socket location can be found using:

  • Inside psql, run \conninfo. It shows the socket location along with other details
  • unix_socket_directory value in postgresql.conf

In my Ubuntu distro, /var/run is a soft link to /run, that's why /run/postgresql works even though unix_socket_directory and \conninfo mention /var/run/postgresql.

Upvotes: 0

Sławosz
Sławosz

Reputation: 11697

Ok, correct connection string is:

"user=postgres host=/tmp dbname=vagrant sslmode=disable"

I assumed pg library uses same defaults as psql or ruby driver. Lesson learned.

Upvotes: 4

Harlam
Harlam

Reputation: 438

Run in console:

psql "user=postgres dbname=vagrant sslmode=disable"

If you cannot connect so it needs to change sslmode else I will think more.

Upvotes: 2

Related Questions