Skip to main content

Connect with Go

This example connects to Redis® service from Go, making use of the go-redis/redis library.

Variables

These are the placeholders you will need to replace in the code sample:

VariableDescription
REDIS_URIURL for the Redis connection, from the service overview page

Prerequisites

Get the go-redis/redis library:

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

Code

Create a new file named main.go, add the following content and replace the placeholder with the Redis URI:

package main

import (
"context"
"fmt"

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

var ctx = context.Background()

func main() {
redisURI := "REDIS_URI"

addr, err := redis.ParseURL(redisURI)
if err != nil {
panic(err)
}

rdb := redis.NewClient(addr)

err = rdb.Set(ctx, "key", "hello world", 0).Err()
if err != nil {
panic(err)
}

val, err := rdb.Get(ctx, "key").Result()
if err != nil {
panic(err)
}
fmt.Println("The value of key is:", val)
}

This code creates a key named key with the value hello world and no expiration time. Then, it gets the key back from Redis and prints its value.

Run the code:

go run main.go

If the script runs successfully, the outputs should be:

The value of key is: hello world