/
utils.go
88 lines (73 loc) · 2.2 KB
/
utils.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package store
import (
"net/url"
"strconv"
"time"
)
// RemoveDSNOptions takes a DSN url string and removes from it any query options
// matching one of the `key` received in parameter.
//
// For example, transforms `kv://path?option1=value&option2=test&option3=any` to
// `kv://path?option2=test` when passing `option1` and `option3` as the keys.
func RemoveDSNOptions(dsn string, keys ...string) (string, error) {
dsnURL, err := url.Parse(dsn)
if err != nil {
return "", err
}
removeDSNOptionsFromURL(dsnURL, keys)
return dsnURL.String(), nil
}
// RemoveDSNOptionsFromURL takes a DSN URL and removes from it any query options
// matching one of the `key` received in parameter.
//
// For example, transforms `kv://path?option1=value&option2=test&option3=any` to
// `kv://path?option2=test` when passing `option1` and `option3` as the keys.
func RemoveDSNOptionsFromURL(dsnURL *url.URL, keys ...string) *url.URL {
copy := &url.URL{
Scheme: dsnURL.Scheme,
Opaque: dsnURL.Opaque,
User: dsnURL.User,
Host: dsnURL.Host,
Path: dsnURL.Path,
RawPath: dsnURL.RawPath,
ForceQuery: dsnURL.ForceQuery,
RawQuery: dsnURL.RawQuery,
Fragment: dsnURL.Fragment,
}
removeDSNOptionsFromURL(copy, keys)
return copy
}
func removeDSNOptionsFromURL(dsnURL *url.URL, keys []string) {
query := dsnURL.Query()
if len(query) <= 0 {
return
}
for _, key := range keys {
query.Del(key)
}
dsnURL.RawQuery = query.Encode()
}
type DSNQuery url.Values
func (q DSNQuery) StringOption(name string, defaultValue string) (value string, rawValue string) {
rawValue = url.Values(q).Get(name)
if rawValue == "" {
return defaultValue, rawValue
}
return rawValue, rawValue
}
func (q DSNQuery) IntOption(name string, defaultValue int) (int, string, error) {
rawValue := url.Values(q).Get(name)
if rawValue == "" {
return defaultValue, rawValue, nil
}
value, err := strconv.Atoi(rawValue)
return value, rawValue, err
}
func (q DSNQuery) DurationOption(name string, defaultValue time.Duration) (time.Duration, string, error) {
rawValue := url.Values(q).Get(name)
if rawValue == "" {
return defaultValue, rawValue, nil
}
value, err := time.ParseDuration(rawValue)
return value, rawValue, err
}