douying9296 2018-08-17 14:52
浏览 386
已采纳

Redigo ScanStruct错误与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.

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条回答 默认 最新

  • dongyuanguang3893 2018-08-17 20:09
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 扫描枪扫条形码出现问题
  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?