use default port if port is missing in dsn (#668) (#669)
diff --git a/README.md b/README.md
index ab1252f..779ada5 100644
--- a/README.md
+++ b/README.md
@@ -101,7 +101,8 @@
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 9cf4bb9..432ca43 100644
--- a/dsn.go
+++ b/dsn.go
@@ -376,6 +376,9 @@
}
}
+ if cfg.Net == "tcp" {
+ cfg.Addr = ensureHavePort(cfg.Addr)
+ }
return
}
@@ -575,3 +578,10 @@
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 671af02..01b5721 100644
--- a/dsn_test.go
+++ b/dsn_test.go
@@ -65,7 +65,14 @@
}, {
"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 {