0

How can I use redis.ScanStruct to parse strings as booleans or even as custom types?

The struct I am using looks like this:

type Attrs struct {
    Secret         string `redis:"secret"`
    RequireSecret  string `redis:"requireSecret"`
    UserID         string `redis:"userId"`
}

The RequireSecret attribute is either a "true" or "false" string, I'd like to scan it as a bool.

4

1 回答 1

2

要扫描 HGETALL 的结果,请使用以下类型

type Attrs struct {
    Secret         string `redis:"secret"`
    RequireSecret  bool `redis:"requireSecret"`
    UserID         string `redis:"userId"`
}

使用以下命令:

values, err := redis.Values(c.Do("HGETALL", key))
if err != nil {
   // handle error
}
var attrs Attrs
err = redis.ScanStruct(values, &attrs)
if err != nil {
   // handle error
}

由于 Redigo 使用strconv.ParseBool将 Redis 结果值转换为bool,因此您无需实现扫描仪接口即可将"true"and转换"false"trueand false

您可以在结构字段的子集上实现扫描仪接口。Redigo 将对不实现接口的字段使用默认解析,对实现接口的字段使用应用程序的自定义解析器。

除非您需要通过 Redis API 访问单个哈希元素,否则通常最好通过使用 JSON、gob 或其他编码器序列化结构来将结构存储为 Redis 字符串。

于 2017-10-23T18:52:28.957 回答