Redigo ScanStruct错误与time.Time [英] Redigo ScanStruct error with time.Time

查看:69
本文介绍了Redigo ScanStruct错误与time.Time的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用redigo的ScanStruct读取具有类型为 time.Time 的字段的结构,这给我带来以下错误:无法从Redis批量字符串转换为time.Time.

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.

解决此问题的唯一方法是创建自己的扩展时间并实现 RedisScan 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...

推荐答案

由于Redis没有时间值的概念,因此对于像redigo这样的通用驱动程序在builin 时间之间执行一些自动转换是没有意义的.时间类型和任意字节数组.因此,由程序员决定如何执行该转换.

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.

例如,假设您已经定义了一个"Person"类型,其中包括一个格式为created_at 时间戳.rel ="nofollow noreferrer"> RFC3339(ISO 8601的一种形式),您可以使用"RedisScan"方法定义自定义"Timestamp"类型,如下所示:

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)

这篇关于Redigo ScanStruct错误与time.Time的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆