Skip to content

Commit 8db6eee

Browse files
authored
feat(scan): scan time.Time sets the default decoding (#2413)
* feat(scan): scan time.Time uses `UnmarshalText(RFC3339)` interface decoding by default
1 parent 9d5e485 commit 8db6eee

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

commands_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1900,6 +1900,25 @@ var _ = Describe("Commands", func() {
19001900
Key2: 123,
19011901
Time: TimeValue{Time: time.Time{}},
19021902
}))
1903+
1904+
type data2 struct {
1905+
Key1 string `redis:"key1"`
1906+
Key2 int `redis:"key2"`
1907+
Time time.Time `redis:"time"`
1908+
}
1909+
err = client.HSet(ctx, "hash", &data2{
1910+
Key1: "hello2",
1911+
Key2: 200,
1912+
Time: now,
1913+
}).Err()
1914+
Expect(err).NotTo(HaveOccurred())
1915+
1916+
var d2 data2
1917+
err = client.HMGet(ctx, "hash", "key1", "key2", "time").Scan(&d2)
1918+
Expect(err).NotTo(HaveOccurred())
1919+
Expect(d2.Key1).To(Equal("hello2"))
1920+
Expect(d2.Key2).To(Equal(200))
1921+
Expect(d2.Time.Unix()).To(Equal(now.Unix()))
19031922
})
19041923

19051924
It("should HIncrBy", func() {

internal/hscan/hscan_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,4 +200,16 @@ var _ = Describe("Scan", func() {
200200
Expect(td.Time.UnixNano()).To(Equal(now.UnixNano()))
201201
Expect(td.Time.Format(time.RFC3339Nano)).To(Equal(now.Format(time.RFC3339Nano)))
202202
})
203+
204+
It("should time.Time RFC3339Nano", func() {
205+
type TimeTime struct {
206+
Time time.Time `redis:"time"`
207+
}
208+
209+
now := time.Now()
210+
211+
var tt TimeTime
212+
Expect(Scan(&tt, i{"time"}, i{now.Format(time.RFC3339Nano)})).NotTo(HaveOccurred())
213+
Expect(now.Unix()).To(Equal(tt.Time.Unix()))
214+
})
203215
})

internal/hscan/structmap.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package hscan
22

33
import (
4+
"encoding"
45
"fmt"
56
"reflect"
67
"strings"
78
"sync"
9+
10+
"github.com/redis/go-redis/v9/internal/util"
811
)
912

1013
// structMap contains the map of struct fields for target structs
@@ -97,8 +100,11 @@ func (s StructValue) Scan(key string, value string) error {
97100
}
98101

99102
if isPtr && v.Type().NumMethod() > 0 && v.CanInterface() {
100-
if scan, ok := v.Interface().(Scanner); ok {
103+
switch scan := v.Interface().(type) {
104+
case Scanner:
101105
return scan.ScanRedis(value)
106+
case encoding.TextUnmarshaler:
107+
return scan.UnmarshalText(util.StringToBytes(value))
102108
}
103109
}
104110

0 commit comments

Comments
 (0)