Go Redis Basic Ops
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
Right
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
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - 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
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