Goal
To integrate the Ziti network dialer into a standard Golang script that connects to a Postgres database
Current progress
The following is what I have worked out to date… but is not complete nor working.
package main
import (
"context"
"fmt"
"os"
// "net/http"
"net"
"time"
"github.com/openziti/sdk-golang/ziti"
"github.com/openziti/sdk-golang/ziti/config"
"github.com/jackc/pgx/v4"
//"github.com/jackc/pgconn"
)
var zitiContext ziti.Context
func Dial(_ context.Context, _ string, addr string) (net.Conn, error) {
service := "private-postgres" //os.Args[2]
defaultOptions := &ziti.DialOptions{ConnectTimeout: 5 * time.Minute}
//zc, err := zitiContext.Dial(service)
zc, err := zitiContext.DialWithOptions(service, defaultOptions)
return zc, err
}
func main() {
cfg, err := config.NewFromFile("/mnt/v/temp/tunneler-id.json")
if err != nil {
panic(err)
}
zitiContext := ziti.NewContextWithConfig(cfg)
identity, err := zitiContext.GetCurrentIdentity()
fmt.Println(identity.Name)
connString := "postgres://postgres:postgres@zitified-postgres:5432/simpledb"
//conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
//conn, err := pgx.Connect(context.Background(), urlExample)
config, err := pgx.ParseConfig(connString)
ctx := context.Background()
// e.g. net.Dialer.DialContext
config.DialFunc = func(ctx context.Context, network string, addr string) (net.Conn, error) {
fmt.Println("dialing")
zitiConn, err := Dial (ctx, "","")
return zitiConn, err
}
conn, err := pgx.ConnectConfig(ctx, config)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer conn.Close(ctx)
rows, err := conn.Query(ctx,`SELECT chardata, somenumber FROM simpletable`)
defer rows.Close()
for rows.Next() {
var chardata string
var somenumber int
err = rows.Scan(&chardata, &somenumber)
fmt.Println(chardata, somenumber)
}
}
The problem
The DialFunc function is not being called to redirect the network connection to the Ziti overlay.
The DialFunc is a part of the lower level libraries that pgx uses. It is found in the pgconn library.
Current understanding
What I believe is happening is that I am using the wrong golang library.
I will update my script to use the pgconn library… which will also require a bit of a rewrite for the query to work
Tips
Am I heading in the right / wrong direction?
Is there an easier way?
I am quite a novice with this… so any tips are greatly appreciated
I am working through this to set up a demo… and need to find a way for this demo to work
PS. I believe this would be a valuable example to add into the Golang SDK examples.