Search code examples
goredisredigo

Scanning "false" and "true" as booleans in Redigo


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.


Solution

  • To scan the result of HGETALL, use the following type

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

    with the following command:

    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
    }
    

    Because Redigo uses strconv.ParseBool to convert Redis result values to bool, you don't need to implement the scanner interface to convert "true" and "false" to true and false.

    You can implement the scanner interface on a subset of a struct's fields. Redigo will use the default parsing for fields that do not implement the interface and the application's custom parser for the fields that do implement the interface.

    Unless you need to access individual hash elements through the Redis API, it's usually better store sructs as a Redis string by serializing the struct using JSON, gob or some other encoder.