-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.go
72 lines (64 loc) · 1.24 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
package memdb
import (
"context"
"fmt"
"net/url"
"reflect"
"strconv"
"time"
"github.com/go-redis/redis/v8"
)
func setOptions(opts *redis.Options, dsn string) {
url, err := url.Parse(dsn)
if err != nil {
panic(err)
}
args := url.Query()
rv := reflect.ValueOf(opts).Elem()
rt := rv.Type()
for i := 0; i < rv.NumField(); i++ {
f := rv.Field(i)
if !f.CanInterface() {
continue
}
name := rt.Field(i).Name
arg := args.Get(name)
if arg == "" {
continue
}
switch f.Interface().(type) {
case time.Duration:
v, err := time.ParseDuration(arg)
if err != nil {
panic(fmt.Sprintf("%s=%s, err:%v", name, arg, err))
}
f.Set(reflect.ValueOf(v))
case int:
v, err := strconv.Atoi(arg)
if err != nil {
panic(fmt.Sprintf("%s=%s, err:%v", name, arg, err))
}
f.SetInt(int64(v))
case bool:
v, err := strconv.ParseBool(arg)
if err != nil {
panic(fmt.Sprintf("%s=%s, err:%v", name, arg, err))
}
f.SetBool(v)
case string:
f.SetString(arg)
}
}
opts.Addr = url.Host
opts.Username = url.User.Username()
if p, ok := url.User.Password(); ok {
opts.Password = p
}
}
func name(ctx context.Context) string {
v, _ := ctx.Value(nameKey{}).(string)
if v == "" {
v = "unknown"
}
return v
}