From 7785c74297136c027fdf2fd6f8931c0e19be8aa7 Mon Sep 17 00:00:00 2001 From: Bulat Gaifullin Date: Thu, 21 Sep 2017 09:28:06 +0300 Subject: [PATCH] use default port if port is missing in dsn (#668) (#669) --- README.md | 3 ++- dsn.go | 10 ++++++++++ dsn_test.go | 9 ++++++++- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ab1252f14..779ada5ba 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,8 @@ See [net.Dial](https://golang.org/pkg/net/#Dial) for more information which netw In general you should use an Unix domain socket if available and TCP otherwise for best performance. #### Address -For TCP and UDP networks, addresses have the form `host:port`. +For TCP and UDP networks, addresses have the form `host[:port]`. +If `port` is omitted, the default port will be used. If `host` is a literal IPv6 address, it must be enclosed in square brackets. The functions [net.JoinHostPort](https://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](https://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form. diff --git a/dsn.go b/dsn.go index 9cf4bb94a..432ca43b8 100644 --- a/dsn.go +++ b/dsn.go @@ -376,6 +376,9 @@ func ParseDSN(dsn string) (cfg *Config, err error) { } } + if cfg.Net == "tcp" { + cfg.Addr = ensureHavePort(cfg.Addr) + } return } @@ -575,3 +578,10 @@ func parseDSNParams(cfg *Config, params string) (err error) { return } + +func ensureHavePort(addr string) string { + if _, _, err := net.SplitHostPort(addr); err != nil { + return net.JoinHostPort(addr, "3306") + } + return addr +} diff --git a/dsn_test.go b/dsn_test.go index 671af020b..01b57212f 100644 --- a/dsn_test.go +++ b/dsn_test.go @@ -65,7 +65,14 @@ var testDSNs = []struct { }, { "unix/?arg=%2Fsome%2Fpath.ext", &Config{Net: "unix", Addr: "/tmp/mysql.sock", Params: map[string]string{"arg": "/some/path.ext"}, Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, -}} +}, { + "tcp(127.0.0.1)/dbname", + &Config{Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, +}, { + "tcp(de:ad:be:ef::ca:fe)/dbname", + &Config{Net: "tcp", Addr: "[de:ad:be:ef::ca:fe]:3306", DBName: "dbname", Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, +}, +} func TestDSNParser(t *testing.T) { for i, tst := range testDSNs {