1
votes

I am trying to conenct to postgres database on a device running ubuntu.

It says "You are connected to database "template1" as user "postgres" via socket in "/var/run/postgresql" at port "5432"."

I guessed that is ok but its not connecting. What is wrong? here is the connection code:

var dbpool, _ = pgxpool.Connect(context.Background(), os.Getenv("postgres:///template1?host=/var/run/postgresql"))  

error from go code

var dbpool, _ = pgxpool.Connect(context.Background(), os.Getenv("postgres://%2Fvar%2Frun%2Fpostgresql/template1"))  
func HelloServer(w http.ResponseWriter, req *http.Request) {

    decoder := json.NewDecoder(req.Body)
    var t test_struct
    err := decoder.Decode(&t)
    if err != nil {
        panic(err)
    }
    log.Println(t)
_, err = dbpool.Exec(ctx,"INSERT INTO users (id,name,surname) VALUES ($1,$2,$3)", t.Id, t.Name,t.Surname)

runtime error: invalid memory address or nil pointer dereference goroutine 7 [running]: net/http.(*conn).serve.func1(0xc000092dc0) /usr/local/go/src/net/http/server.go:1824 +0x153 panic(0x7ea0e0, 0xad7860) /usr/local/go/src/runtime/panic.go:971 +0x499 github.com/jackc/pgx/v4/pgxpool.(*Pool).Acquire(0x0, 0x8cd250, 0xc0000240e0, 0x10, 0x7ffa25841108, 0x10) /root/go/pkg/mod/github.com/jackc/pgx/[email protected]/pgxpool/pool.go:380 +0x31 github.com/jackc/pgx/v4/pgxpool.(*Pool).Exec(0x0, 0x8cd250, 0xc0000240e0, 0x85f063, 0x36, 0xc000103aa8, 0x3, 0x3, 0x0, 0x0, ...) /root/go/pkg/mod/github.com/jackc/pgx/[email protected]/pgxpool/pool.go:432 +0x86 main.HelloServer(0x8cbcc0, 0xc0000e22a0, 0xc000134100) /root/goservertls.go:41 +0x2b1 net/http.HandlerFunc.ServeHTTP(0x86d7e0, 0x8cbcc0, 0xc0000e22a0, 0xc000134100) /usr/local/go/src/net/http/server.go:2069 +0x44 net/http.(*ServeMux).ServeHTTP(0xae6be0, 0x8cbcc0, 0xc0000e22a0, 0xc000134100) /usr/local/go/src/net/http/server.go:2448 +0x1ad net/http.serverHandler.ServeHTTP(0xc0000e20e0, 0x8cbcc0, 0xc0000e22a0, 0xc000134100) /usr/local/go/src/net/http/server.go:2887 +0xa3 net/http.(*conn).serve(0xc000092dc0, 0x8cd2c0, 0xc0000634c0) /usr/local/go/src/net/http/server.go:1952 +0x8cd created by net/http.(*Server).Serve /usr/local/go/src/net/http/server.go:3013 +0x39b

1

1 Answers

1
votes

The host needs to go in the host position of the URI, not just tacked on at the end. But since it includes literal /, those need to be URI encoded.

 postgres://%2Fvar%2Frun%2Fpostgresql/template1