'Go Redis convert HGetAll result to struct
I'm getting data from the redis.HGetAll but found no clean way to convert results into my Struct.
var object struct {
x int
}
result := redisClient.HGetAll(context.Background(), "the_h_key")
//TODO import the result content into the object
Is there any function for this spectacular case?
I'm using the JSON package(marshal, then UnMarshal to a struct).
Solution 1:[1]
The result from Redis is a map[string]string. For each field in the struct, get the value from the map, convert the string to the field type and assign to the field.
var o object
var err error
o.x, err = strconv.Atoi(m["x"])
if err != nil {
// handle the error
}
... repeat for other fields as needed
Solution 2:[2]
If your datastructure isn't too complex, one convenient way to save data using redis is as jsons. Just json.Marhsal() your struct and save it as a string and then json.Unmarshal() that string into your struct back.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Taylor Rex |
| Solution 2 | Vaibhav Mishra |
