问题
I am trying to read a struct that has a field of type time.Time using redigo's ScanStruct, which gives me the following error: cannot convert from Redis bulk string to time.Time.
Is the only way of fixing this to create my own time type that extends time.Time and implements RedisScan? That sounds bad as well...
回答1:
Since Redis has no concept of time values it would make no sense for a generic driver such as redigo to perform some automatic conversion between the builin time.Time type and an arbitrary byte array. As such, it's up to the programmer to decide how to perform that conversion.
For example, supposing you have a "Person" type defined as such, including a created_at timestamp formatted as RFC3339 (a form of ISO 8601), you could define a custom "Timestamp" type with a "RedisScan" method as follows:
type Timestamp time.Time
type Person struct {
Id int `redis:"id"`
Name string `redis:"name"`
CreatedAt Timestamp `redis:"created_at"`
}
func (t *Timestamp) RedisScan(x interface{}) error {
bs, ok := x.([]byte)
if !ok {
return fmt.Errorf("expected []byte, got %T", x)
}
tt, err := time.Parse(time.RFC3339, string(bs))
if err != nil {
return err
}
*t = Timestamp(tt)
return nil
}
// ...
response, err := redis.Values(conn.Do("HGETALL", "person:1"))
if err != nil {
panic(err)
}
var p Person
err = redis.ScanStruct(response, &p)
if err != nil {
panic(err)
}
log.Printf("OK: p=%v", p)
来源:https://stackoverflow.com/questions/51897965/redigo-scanstruct-error-with-time-time