Skip to content

Commit 600f166

Browse files
committed
Add missing error checks and support for MGET in Scan()
1 parent e113512 commit 600f166

File tree

2 files changed

+52
-3
lines changed

2 files changed

+52
-3
lines changed

command.go

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -375,9 +375,21 @@ func (cmd *SliceCmd) String() string {
375375
// Scan scans the results from the map into a destination struct. The map keys
376376
// are matched in the Redis struct fields by the `redis:"field"` tag.
377377
func (cmd *SliceCmd) Scan(dest interface{}) error {
378-
// Pass the list of keys and values. Skip the first to args (command, key),
379-
// eg: HMGET map.
380-
return hscan.Scan(cmd.args[2:], cmd.val, dest)
378+
if cmd.err != nil {
379+
return cmd.err
380+
}
381+
382+
// Pass the list of keys and values.
383+
// Skip the first two args for: HMGET key
384+
var args []interface{}
385+
if cmd.args[0] == "hmget" {
386+
args = cmd.args[2:]
387+
} else {
388+
// Otherwise, it's: MGET field field ...
389+
args = cmd.args[1:]
390+
}
391+
392+
return hscan.Scan(args, cmd.val, dest)
381393
}
382394

383395
func (cmd *SliceCmd) readReply(rd *proto.Reader) error {
@@ -929,6 +941,10 @@ func (cmd *StringStringMapCmd) String() string {
929941
// Scan scans the results from the map into a destination struct. The map keys
930942
// are matched in the Redis struct fields by the `redis:"field"` tag.
931943
func (cmd *StringStringMapCmd) Scan(dest interface{}) error {
944+
if cmd.err != nil {
945+
return cmd.err
946+
}
947+
932948
// Pass the list of keys and values. Skip the first to args (command, key),
933949
// eg: HGETALL map.
934950
var (

example_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,39 @@ func ExampleStringStringMapCmd_Scan() {
310310
// Output: {hello 123 true}
311311
}
312312

313+
// ExampleSliceCmd_Scan shows how to scan the results of a multi key fetch
314+
// into a struct.
315+
func ExampleSliceCmd_Scan() {
316+
rdb.FlushDB(ctx)
317+
err := rdb.MSet(ctx,
318+
"name", "hello",
319+
"count", 123,
320+
"correct", true).Err()
321+
if err != nil {
322+
panic(err)
323+
}
324+
325+
res := rdb.MGet(ctx, "name", "count", "empty", "correct")
326+
if res.Err() != nil {
327+
panic(err)
328+
}
329+
330+
type data struct {
331+
Name string `redis:"name"`
332+
Count int `redis:"count"`
333+
Correct bool `redis:"correct"`
334+
}
335+
336+
// Scan the results into the struct.
337+
var d data
338+
if err := res.Scan(&d); err != nil {
339+
panic(err)
340+
}
341+
342+
fmt.Println(d)
343+
// Output: {hello 123 true}
344+
}
345+
313346
func ExampleClient_Pipelined() {
314347
var incr *redis.IntCmd
315348
_, err := rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {

0 commit comments

Comments
 (0)