-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
147 lines (112 loc) · 2.3 KB
/
parser.go
File metadata and controls
147 lines (112 loc) · 2.3 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package parser
import (
"errors"
"strings"
)
var (
ErrorProtocolNotFound = errors.New("protocol not found")
ErrorHostsNotFound = errors.New("hosts not found")
ErrorHostNameCanNotBeEmpty = errors.New("host name can't be empty")
)
type DSN struct {
Dsn string
Protocol string
*Auth
Hosts []*Host
Database string
Options map[string]string
}
type Auth struct {
User string
Password string
}
type Host struct {
Host string
Port string
}
func New(dsn string) (*DSN, error) {
obj := &DSN{
Dsn: dsn,
Options: make(map[string]string),
Auth: &Auth{},
}
dsn, err := obj.parseProtocol(dsn)
if err != nil {
return nil, err
}
index := strings.Index(dsn, "@")
if index > -1 {
tmp := dsn[0:index]
data := strings.Split(tmp, ":")
if len(data) == 2 {
obj.Auth.User = data[0]
obj.Auth.Password = data[1]
} else {
obj.Auth.User = data[0]
}
dsn = dsn[index+1:]
}
index = strings.Index(dsn, "?")
if index > -1 && !strings.Contains(dsn, "/") {
dsn = strings.Replace(dsn, "?", "/?", 1)
}
data := strings.Split(dsn, "/")
err = obj.parseHosts(data[0])
if err != nil {
return nil, err
}
if len(data) == 2 {
tmp := strings.Split(data[1], "?")
if len(tmp[0]) > 0 {
obj.Database = tmp[0]
}
if len(tmp) == 2 && len(tmp[1]) > 0 {
obj.parseOptions(tmp[1])
}
}
return obj, nil
}
func (m *DSN) parseProtocol(dsn string) (string, error) {
index := strings.Index(dsn, "://")
if index == -1 {
return "", ErrorProtocolNotFound
}
protocol := dsn[0:index]
if protocol == "" {
return "", ErrorProtocolNotFound
}
m.Protocol = protocol
return dsn[index+3:], nil
}
func (m *DSN) parseHosts(hosts string) error {
if len(hosts) <= 0 {
return ErrorHostsNotFound
}
splitHosts := strings.Split(hosts, ",")
for _, v := range splitHosts {
tmp := strings.Split(v, ":")
if tmp[0] == "" {
return ErrorHostNameCanNotBeEmpty
}
host := &Host{}
if len(tmp) == 2 {
host.Host = tmp[0]
host.Port = tmp[1]
} else {
host.Host = tmp[0]
}
m.Hosts = append(m.Hosts, host)
}
return nil
}
func (m *DSN) parseOptions(opts string) {
optsSplit := strings.Split(opts, "&")
for _, v := range optsSplit {
opt := strings.Split(v, "=")
if len(opt) == 1 {
m.Options[opt[0]] = ""
} else {
m.Options[opt[0]] = opt[1]
}
}
}