I have a redis hash that has a key "has_ended" that I want to convert to a boolean value.
someMap, _ := rv.redis.HGetAll(key).Result() // returns map[string]interface{}
hasEnded := someMap["has_ended"]
If the key "has_ended" isn't present in the map and I try to convert it to a boolean it will crash. How can I write this safely?
Assuming that you are using the popular github.com/go-redis/redis package, the return value from HGetAll(key).Result()
is a map[string]string
(doc). The expression someMap["has_ended"]
evaluates to the empty string if the key is not present.
If hasEnded is true if and only if the key is present with the value "true", then use the following:
hasEnded := someMap["has_ended"] == "true"
Use strconv.ParseBool to a handle a wider range of possible values (1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False):
hasEnded, err := strconv.ParseBool(someMap["has_ended"])
if err != nil {
// handle invalid value or missing value, possibly by setting hasEnded to false
}