浏览代码

use default port if port is missing in dsn (#668) (#669)

Bulat Gaifullin 8 年之前
父节点
当前提交
7785c74297
共有 3 个文件被更改,包括 20 次插入2 次删除
  1. 2 1
      README.md
  2. 10 0
      dsn.go
  3. 8 1
      dsn_test.go

+ 2 - 1
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.
 In general you should use an Unix domain socket if available and TCP otherwise for best performance.
 
 
 #### Address
 #### 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.
 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.
 The functions [net.JoinHostPort](https://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](https://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form.
 
 

+ 10 - 0
dsn.go

@@ -376,6 +376,9 @@ func ParseDSN(dsn string) (cfg *Config, err error) {
 		}
 		}
 
 
 	}
 	}
+	if cfg.Net == "tcp" {
+		cfg.Addr = ensureHavePort(cfg.Addr)
+	}
 
 
 	return
 	return
 }
 }
@@ -575,3 +578,10 @@ func parseDSNParams(cfg *Config, params string) (err error) {
 
 
 	return
 	return
 }
 }
+
+func ensureHavePort(addr string) string {
+	if _, _, err := net.SplitHostPort(addr); err != nil {
+		return net.JoinHostPort(addr, "3306")
+	}
+	return addr
+}

+ 8 - 1
dsn_test.go

@@ -65,7 +65,14 @@ var testDSNs = []struct {
 }, {
 }, {
 	"unix/?arg=%2Fsome%2Fpath.ext",
 	"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},
 	&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) {
 func TestDSNParser(t *testing.T) {
 	for i, tst := range testDSNs {
 	for i, tst := range testDSNs {