Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io/fs"
"net"
"net/url"
"os"
"path/filepath"
Expand Down Expand Up @@ -230,6 +231,9 @@ func (d Database) buildDSN() string {
if host == "" {
host = "127.0.0.1"
}
// A bare IPv6 address needs brackets in a URL authority; JoinHostPort adds
// them, so drop any the operator already typed.
host = strings.TrimSuffix(strings.TrimPrefix(host, "["), "]")
port := d.Port
if port == 0 {
port = 5432
Expand All @@ -240,7 +244,7 @@ func (d Database) buildDSN() string {
}
u := url.URL{
Scheme: "postgres",
Host: host + ":" + strconv.Itoa(port),
Host: net.JoinHostPort(host, strconv.Itoa(port)),
Path: "/" + d.DBName,
}
if d.User != "" {
Expand Down
28 changes: 28 additions & 0 deletions config/dsn_host_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package config

import (
"testing"

"github.com/jackc/pgx/v5/pgconn"
)

func TestBuildDSNHost(t *testing.T) {
cases := []struct{ host, want string }{
{"", "127.0.0.1"},
{"db.internal", "db.internal"},
{"10.0.0.5", "10.0.0.5"},
{"::1", "::1"},
{"2001:db8::5", "2001:db8::5"},
{"[2001:db8::5]", "2001:db8::5"},
}
for _, tc := range cases {
dsn := Database{Host: tc.host, Port: 5433, User: "u", DBName: "artex"}.buildDSN()
cfg, err := pgconn.ParseConfig(dsn)
if err != nil {
t.Fatalf("host %q: DSN %q does not parse: %v", tc.host, dsn, err)
}
if cfg.Host != tc.want || cfg.Port != 5433 {
t.Errorf("host %q: pgx reads host %q port %d from %q, want %q 5433", tc.host, cfg.Host, cfg.Port, dsn, tc.want)
}
}
}
Loading