Skip to content

Commit bf334e7

Browse files
committed
feat: enable struct on HSet
1 parent e9a8bb4 commit bf334e7

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

commands.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"errors"
66
"io"
7+
"reflect"
78
"time"
89

910
"github.com/go-redis/redis/v8/internal"
@@ -78,6 +79,29 @@ func appendArg(dst []interface{}, arg interface{}) []interface{} {
7879
}
7980
}
8081

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+
81105
type Cmdable interface {
82106
Pipeline() Pipeliner
83107
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
12611285
// - HSet("myhash", "key1", "value1", "key2", "value2")
12621286
// - HSet("myhash", []string{"key1", "value1", "key2", "value2"})
12631287
// - HSet("myhash", map[string]interface{}{"key1": "value1", "key2": "value2"})
1288+
// - HSet("myhash", struct{Key1: "value1"; Key2: "value2"})
12641289
//
12651290
// Note that it requires Redis v4 for multiple field/value pairs support.
12661291
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+
}
12671297
args := make([]interface{}, 2, 2+len(values))
12681298
args[0] = "hset"
12691299
args[1] = key

example_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,20 @@ func ExampleClient_SetEX() {
197197
}
198198
}
199199

200+
func ExampleClient_HSet() {
201+
type Items struct {
202+
Key1 string `json:"key1"`
203+
Key2 string `json:"key2"`
204+
}
205+
items := Items{"field1", "field2"}
206+
// Last argument is expiration. Zero means the key has no
207+
// expiration time.
208+
err := rdb.HSet(ctx, "key", items).Err()
209+
if err != nil {
210+
panic(err)
211+
}
212+
}
213+
200214
func ExampleClient_Incr() {
201215
result, err := rdb.Incr(ctx, "counter").Result()
202216
if err != nil {

0 commit comments

Comments
 (0)