-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
dsn.go
62 lines (54 loc) Β· 1.17 KB
/
dsn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package config
import "regexp"
// dsnPattern is a regular expression matching a database DSN string.
var dsnPattern = regexp.MustCompile(
`^((?P<driver>.*):\/\/)?(?:(?P<user>.*?)(?::(?P<password>.*))?@)?` +
`(?:(?P<net>[^\(]*)(?:\((?P<server>[^\)]*)\))?)?` +
`\/(?P<name>.*?)` +
`(?:\?(?P<params>[^\?]*))?$`)
// DSN represents parts of a data source name.
type DSN struct {
Driver string
User string
Password string
Net string
Server string
Name string
Params string
}
// NewDSN creates a new DSN struct from a string.
func NewDSN(dsn string) DSN {
d := DSN{}
d.Parse(dsn)
return d
}
// Parse parses a data source name string.
func (d *DSN) Parse(dsn string) {
if dsn == "" {
return
}
matches := dsnPattern.FindStringSubmatch(dsn)
names := dsnPattern.SubexpNames()
for i, match := range matches {
switch names[i] {
case "driver":
d.Driver = match
case "user":
d.User = match
case "password":
d.Password = match
case "net":
d.Net = match
case "server":
d.Server = match
case "name":
d.Name = match
case "params":
d.Params = match
}
}
if d.Net != "" && d.Server == "" {
d.Server = d.Net
d.Net = ""
}
}