-
Notifications
You must be signed in to change notification settings - Fork 566
/
url.go
70 lines (62 loc) · 1.38 KB
/
url.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
63
64
65
66
67
68
69
70
package pachsql
import (
"net/url"
"strconv"
"strings"
"github.com/pachyderm/pachyderm/v2/src/internal/errors"
)
// URL contains the information needed to connect to a SQL database, except for the password.
type URL struct {
Protocol string
User string
Host string
Port uint16
Database string
Schema string
Params map[string]string
}
// ParseURL attempts to parse x into a URL
func ParseURL(x string) (*URL, error) {
u, err := url.Parse(x)
if err != nil {
return nil, errors.EnsureStack(err)
}
var port int
if u.Port() != "" {
port, err = strconv.Atoi(u.Port())
if err != nil {
return nil, errors.EnsureStack(errors.Wrapf(err, "parsing url port: %w"))
}
}
params := make(map[string]string)
for k, v := range u.Query() {
if len(v) > 0 {
params[k] = v[len(v)-1]
}
}
// parse database name and schema
// assume /dbname/schemaname
var dbname, schemaname string
parts := strings.SplitN(strings.Trim(u.Path, "/"), "/", 2)
dbname = parts[0]
if len(parts) == 2 {
schemaname = parts[1]
}
return &URL{
Protocol: u.Scheme,
Host: u.Hostname(),
Port: uint16(port),
User: u.User.Username(),
Database: dbname,
Schema: schemaname,
Params: params,
}, nil
}
func (u *URL) String() string {
return (&url.URL{
Scheme: u.Protocol,
Host: u.Host,
User: url.UserPassword(u.User, ""),
Path: u.Database,
}).String()
}