From fb42201c18fcd016c235d4b613f76b2fc1599588 Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Fri, 14 May 2021 18:39:31 -0500 Subject: [PATCH] Fix default host when parsing URL without host but with port fixes https://github.com/jackc/pgconn/issues/72 --- config.go | 8 ++++++-- config_test.go | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/config.go b/config.go index 6991e1de..16480589 100644 --- a/config.go +++ b/config.go @@ -411,8 +411,12 @@ func parseURLSettings(connString string) (map[string]string, error) { if err != nil { return nil, fmt.Errorf("failed to split host:port in '%s', err: %w", host, err) } - hosts = append(hosts, h) - ports = append(ports, p) + if h != "" { + hosts = append(hosts, h) + } + if p != "" { + ports = append(ports, p) + } } if len(hosts) > 0 { settings["host"] = strings.Join(hosts, ",") diff --git a/config_test.go b/config_test.go index 11dd23dc..d29173d1 100644 --- a/config_test.go +++ b/config_test.go @@ -32,6 +32,10 @@ func TestParseConfig(t *testing.T) { } } + config, err := pgconn.ParseConfig("") + require.NoError(t, err) + defaultHost := config.Host + tests := []struct { name string connString string @@ -428,6 +432,20 @@ func TestParseConfig(t *testing.T) { }, }, }, + // https://github.com/jackc/pgconn/issues/72 + { + name: "URL without host but with port still uses default host", + connString: "postgres://jack:secret@:1/mydb?sslmode=disable", + config: &pgconn.Config{ + User: "jack", + Password: "secret", + Host: defaultHost, + Port: 1, + Database: "mydb", + TLSConfig: nil, + RuntimeParams: map[string]string{}, + }, + }, { name: "DSN multiple hosts one port", connString: "user=jack password=secret host=foo,bar,baz port=5432 dbname=mydb sslmode=disable",