|
4 | 4 | "context"
|
5 | 5 | "errors"
|
6 | 6 | "io"
|
| 7 | + "reflect" |
7 | 8 | "time"
|
8 | 9 |
|
9 | 10 | "github.com/go-redis/redis/v8/internal"
|
@@ -78,6 +79,29 @@ func appendArg(dst []interface{}, arg interface{}) []interface{} {
|
78 | 79 | }
|
79 | 80 | }
|
80 | 81 |
|
| 82 | +func structToMap(items interface{}) map[string]interface{} { |
| 83 | + res := map[string]interface{}{} |
| 84 | + if items == nil { |
| 85 | + return res |
| 86 | + } |
| 87 | + v := reflect.TypeOf(items) |
| 88 | + reflectValue := reflect.Indirect(reflect.ValueOf(items)) |
| 89 | + |
| 90 | + if v.Kind() == reflect.Ptr { |
| 91 | + v = v.Elem() |
| 92 | + } |
| 93 | + for i := 0; i < v.NumField(); i++ { |
| 94 | + tag := v.Field(i).Tag.Get("json") |
| 95 | + |
| 96 | + if tag != "" && v.Field(i).Type.Kind() != reflect.Struct { |
| 97 | + field := reflectValue.Field(i).Interface() |
| 98 | + res[tag] = field |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + return res |
| 103 | +} |
| 104 | + |
81 | 105 | type Cmdable interface {
|
82 | 106 | Pipeline() Pipeliner
|
83 | 107 | Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error)
|
@@ -1261,9 +1285,15 @@ func (c cmdable) HMGet(ctx context.Context, key string, fields ...string) *Slice
|
1261 | 1285 | // - HSet("myhash", "key1", "value1", "key2", "value2")
|
1262 | 1286 | // - HSet("myhash", []string{"key1", "value1", "key2", "value2"})
|
1263 | 1287 | // - HSet("myhash", map[string]interface{}{"key1": "value1", "key2": "value2"})
|
| 1288 | +// - HSet("myhash", struct{Key1: "value1"; Key2: "value2"}) |
1264 | 1289 | //
|
1265 | 1290 | // Note that it requires Redis v4 for multiple field/value pairs support.
|
1266 | 1291 | func (c cmdable) HSet(ctx context.Context, key string, values ...interface{}) *IntCmd {
|
| 1292 | + if len(values) == 1 { |
| 1293 | + if reflect.ValueOf(values[0]).Kind() == reflect.Struct { |
| 1294 | + values = []interface{}{structToMap(values[0])} |
| 1295 | + } |
| 1296 | + } |
1267 | 1297 | args := make([]interface{}, 2, 2+len(values))
|
1268 | 1298 | args[0] = "hset"
|
1269 | 1299 | args[1] = key
|
|
0 commit comments