I have a map like this, which I want to save/retrive from redis using redigo:
animals := map[string]bool{
"cat": true,
"dog": false,
"fox": true,
}
The length of the map may vary.
I tried these function:
func SetHash(key string, value map[string]bool) error {
conn := Pool.Get()
defer conn.Close()
_, err := conn.Do("HMSET", key, value)
if err != nil {
return fmt.Errorf("error setting key %s to %s: %v", key, value, err)
}
return err
}
func GetHash(key string) (map[string]bool, error) {
conn := Pool.Get()
defer conn.Close()
val, err := conn.Do("HGETALL", key)
if err != nil {
fmt.Errorf("error setting key %s to %s: %v", key, nil, err)
return nil, err
}
return val, err
}
But can not make GetHash
correctly. I’ve checked the docs examples and it was not helpful. So appreciate your help to have a working example.
2
Answers
The application is responsible for converting structured types to and from the types understood by Redis.
Flatten the map into a list of arguments:
Convert the returned field value pairs to a map:
HMSET
is deprecated, useHSET
instead, no effect here though.The
map[string]bool
may be flattened withAddFlat()
forSetHash()
.For
GetHash()
, useValues()
. You may useScanStruct()
to map to a struct or loop through the values to create a map dynamically.See example from redigo tests in scan_test.go.