0

I am having trouble creating a connection to a postgres database via ssh tunneling with the "github.com/jackc/pgx/v4/pgxpool" library. I cannot seem to figure out how to set the DialFunc for the *pgxpool.Config that I would like to use to establish a connection. This is what I'm trying to do:

        sshConnStr := mkPostgresXViaSSHConnStr(config, tz)
        
        config, err := parseSshConnStr(sshConnStr)
        // var config *pgsshConfig

        sshcon, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", config.tunnelHost, config.tunnelConfig), &config.tunnelConfig)
        // var sshcon *ssh.Client

        cfg, err = pgxpool.ParseConfig(config.pgConnStr)
        // var cfg *pgxpool.Config

        cfg.ConnConfig.DialFunc = func(network, addr string) (net.Conn, error) {
            return sshcon.Dial(network, addr)
        }

When I try to set the DialFunc I get the following error: cannot use (func(network, addr string) (net.Conn, error) literal) (value of type func(network string, addr string) (net.Conn, error)) as pgconn.DialFunc value in assignment

Any suggestions about how to get this to work?

2 Answers2

0

Add context and cast to pgconn.DialFunc:

package main

import (
        "context"
        "net"

        "github.com/jackc/pgconn"
        "github.com/jackc/pgx/v4/pgxpool"
)

func main() {
        cfg, _ := pgxpool.ParseConfig("")
        myDial := func(ctx context.Context, network, addr string) (net.Conn, error) {
                return nil, nil
        }
        cfg.ConnConfig.DialFunc = pgconn.DialFunc(myDial)
}
serge-v
  • 750
  • 2
  • 8
  • I get two strange errors when I do that. The first: `DialFunc not declared by package pgx` even though I can see that it is.... and if I try to convert it to pgconn.DialFunc: `cfg.ConnConfig.DialFunc = pgconn.DialFunc(myDeal)` I get this error: `cannot convert myDeal (variable of type func(network string, addr string) (net.Conn, error)) to pgconn.DialFunc1` – user17976520 Jan 19 '22 at 19:24
  • @user17976520 sorry, used wrong import. Fixed now. – serge-v Jan 19 '22 at 20:40
  • Is the casting necessary? – viggy28 Feb 28 '23 at 06:27
0

I was looking at the wrong type for the DialFunc. For pgx/v3.6.2 only the network and address were needed as parameters. In the updated version, pgx/v4 context.Context needs to be passed as a variable as well (whether or not it is actually used). The update which fixed the error is this:


cfg.ConnConfig.DialFunc = func(ctx context.Context, network, addr string) (net.Conn, error) {
            return sshcon.Dial(network, addr)
}

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 20 '22 at 00:16