github.com/aaabigfish/gopkg@v1.1.0/cache/redis/unit.go (about) 1 package redis 2 3 import ( 4 "fmt" 5 "net/url" 6 "reflect" 7 "strconv" 8 "strings" 9 "time" 10 11 gredis "github.com/redis/go-redis/v9" 12 ) 13 14 func setOptions(opts *gredis.UniversalOptions, dsn string) { 15 url, err := url.Parse(dsn) 16 if err != nil { 17 panic(err) 18 } 19 20 args := url.Query() 21 22 rv := reflect.ValueOf(opts).Elem() 23 rt := rv.Type() 24 25 for i := 0; i < rv.NumField(); i++ { 26 f := rv.Field(i) 27 if !f.CanInterface() { 28 continue 29 } 30 name := rt.Field(i).Name 31 arg := args.Get(name) 32 if arg == "" { 33 continue 34 } 35 switch f.Interface().(type) { 36 case time.Duration: 37 v, err := time.ParseDuration(arg) 38 if err != nil { 39 panic(fmt.Sprintf("%s=%s, err:%v", name, arg, err)) 40 } 41 f.Set(reflect.ValueOf(v)) 42 case int: 43 v, err := strconv.Atoi(arg) 44 if err != nil { 45 panic(fmt.Sprintf("%s=%s, err:%v", name, arg, err)) 46 } 47 f.SetInt(int64(v)) 48 case bool: 49 v, err := strconv.ParseBool(arg) 50 if err != nil { 51 panic(fmt.Sprintf("%s=%s, err:%v", name, arg, err)) 52 } 53 f.SetBool(v) 54 case string: 55 f.SetString(arg) 56 } 57 } 58 59 opts.Addrs = []string{url.Host} 60 opts.Username = url.User.Username() 61 if p, ok := url.User.Password(); ok { 62 opts.Password = p 63 } 64 65 // 获取database 66 f := strings.FieldsFunc(url.Path, func(r rune) bool { 67 return r == '/' 68 }) 69 switch len(f) { 70 case 0: 71 opts.DB = 0 72 case 1: 73 var err error 74 if opts.DB, err = strconv.Atoi(f[0]); err != nil { 75 panic(fmt.Sprintf("redis: invalid database number: %q", f[0])) 76 } 77 default: 78 panic(fmt.Sprintf("redis: invalid URL path: %s", url.Path)) 79 } 80 }