Fix default host when parsing URL without host but with port

fixes https://github.com/jackc/pgconn/issues/72
query-exec-mode
Jack Christensen 2021-05-14 18:39:31 -05:00
parent 3f76b98073
commit fb42201c18
2 changed files with 24 additions and 2 deletions

View File

@ -411,8 +411,12 @@ func parseURLSettings(connString string) (map[string]string, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to split host:port in '%s', err: %w", host, err) return nil, fmt.Errorf("failed to split host:port in '%s', err: %w", host, err)
} }
hosts = append(hosts, h) if h != "" {
ports = append(ports, p) hosts = append(hosts, h)
}
if p != "" {
ports = append(ports, p)
}
} }
if len(hosts) > 0 { if len(hosts) > 0 {
settings["host"] = strings.Join(hosts, ",") settings["host"] = strings.Join(hosts, ",")

View File

@ -32,6 +32,10 @@ func TestParseConfig(t *testing.T) {
} }
} }
config, err := pgconn.ParseConfig("")
require.NoError(t, err)
defaultHost := config.Host
tests := []struct { tests := []struct {
name string name string
connString 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", name: "DSN multiple hosts one port",
connString: "user=jack password=secret host=foo,bar,baz port=5432 dbname=mydb sslmode=disable", connString: "user=jack password=secret host=foo,bar,baz port=5432 dbname=mydb sslmode=disable",