Is it possible to check straight away if the key was found before doing more processing on the result?
res := client.HGetAll(ctx, key)
err := res.Err()
if err != nil {
panic("Redis hgetall: "+err.Error())
}
When fetching a key you can do err == redis.Nil
value, err := client.Get(ctx, key).Result()
empty := err == redis.Nil
if err != nil && !empty {
panic("Redis get: "+err.Error())
}
return value, !empty
2
Answers
Assuming the key does not exist:
For the GET command, redis-server does return a
(nil)
response hence you can check for theredis.Nil
error.For the HGETALL command, redis-server will return something along the lines of
(empty list or set)
which is not the same as nil hence why the library authors (go-redis) may have decided that it is not worthy of returning a redis.Nil error (or any similar error).Your best bet would be to check if the returned "list or set" (
res.Val()
) is empty.Yes. Here is an example of how to find the state of the operation:
Read more in
go-redis
docsYou can also use
Exists
to check if a key exists.