go-redis guide (Go)

Connect your Go application to a Redis database

go-redis is the Go client for Redis. The sections below explain how to install go-redis and connect your application to a Redis database.

go-redis requires a running Redis server. See here for Redis Open Source installation instructions.

Install

go-redis supports the last two Go versions. You can only use it from within a Go module, so you must initialize a Go module before you start, or add your code to an existing module:

go mod init github.com/my/repo

Use the go get command to install go-redis/v9:

go get github.com/redis/go-redis/v9

Connect

The following example shows the simplest way to connect to a Redis server. First, import the go-redis package:

Foundational: Import the go-redis package

package main

import (
    "context"
    "fmt"

"github.com/redis/go-redis/v9"
)

func main() {
    rdb := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password
        DB:       0,  // use default DB
        Protocol: 2,
    })

ctx := context.Background()

err := rdb.Set(ctx, "foo", "bar", 0).Err()
    if err != nil {
        panic(err)
    }

val, err := rdb.Get(ctx, "foo").Result()
    if err != nil {
        panic(err)
    }
    fmt.Println("foo", val) // >>> foo bar

hashFields := []string{
        "model", "Deimos",
        "brand", "Ergonom",
        "type", "Enduro bikes",
        "price", "4972",
    }

res1, err := rdb.HSet(ctx, "bike:1", hashFields).Result()

if err != nil {
        panic(err)
    }

fmt.Println(res1) // >>> 4

res2, err := rdb.HGet(ctx, "bike:1", "model").Result()

if err != nil {
        panic(err)
    }

fmt.Println(res2) // >>> Deimos

res3, err := rdb.HGet(ctx, "bike:1", "price").Result()

if err != nil {
        panic(err)
    }

fmt.Println(res3) // >>> 4972

res4, err := rdb.HGetAll(ctx, "bike:1").Result()

if err != nil {
        panic(err)
    }

fmt.Println(res4)
    // >>> map[brand:Ergonom model:Deimos price:4972 type:Enduro bikes]

type BikeInfo struct {
        Model string ` + '`' + `redis: