Skip to content

Go Redis Basic Ops

DodaTech 1 min read

In this tutorial, you'll learn about Go Redis: Basic Operations. We cover key concepts, practical examples, and best practices.

Redis basic operations -- Use go-redis for basic key-value operations with proper error handling.

The Problem

go-redis commands return errors for connection issues. Ignoring the error and using the value leads to zero-value results. Always check errors.

Wrong

val := rdb.Get(ctx, "key").Val()
fmt.Println(val)

Output:

// If connection fails, val is "" with no indication of error
val, err := rdb.Get(ctx, "key").Result()
if err == redis.Nil {
    fmt.Println("Key not found")
} else if err != nil {
    log.Fatal(err)
} else {
    fmt.Println("Value:", val)
}

Output:

Value: hello

Prevention

  • Use .Result() to get (value, error)
  • Use .Val() only when you don't care about errors
  • Check for redis.Nil to detect missing keys
  • Use Set, Get, Del, Exists for basic ops
  • Use Expire to set TTL

Common Mistakes with redis basic ops

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**How to set key with expiration?**

rdb.Set(ctx, "key", "value", 10*time.Minute).Err().

How to check if key exists?

rdb.Exists(ctx, "key").Val() returns 1 or 0.

How to delete a key?

rdb.Del(ctx, "key").Err().


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro