check if HGetAll is found

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

Assuming the key does not exist:

For the GET command, redis-server does return a (nil) response hence you can check for the redis.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:

val, err := rdb.Get(ctx, "key").Result()
switch {
case err == redis.Nil:
    fmt.Println("key does not exist")
case err != nil:
    fmt.Println("Get failed", err)
case val == "":
    fmt.Println("value is empty")
}

Read more in go-redis docs

You can also use Exists to check if a key exists.

Leave a Comment