Skip to content

Go Redis CRUD operations

This guide outlines the implementation of Create, Read, Update, and Delete (CRUD) operations for a Go application using a Redis database. It covers migrating from local file storage to a Redis-backed repository, including connection setup and basic data manipulation.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

Prerequisites and Setup

To perform Redis operations in Go, the go-redis client library is required^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. The library must be imported into the application, typically using github.com/go-redis/redis/v8.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

Connecting to Redis

A connection to Redis is established using a client instance. In a typical setup involving high availability, a FailoverClient is used to handle Sentinel-managed Redis instances^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. Configuration details such as sentinel addresses and master names are often supplied via environment variables^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

A background context is required for the client operations^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

import (
    "context"
    "github.com/go-redis/redis/v8"
    "strings"
)

var ctx = context.Background()

sentinelAddrs := strings.Split(redis_sentinels, ",")
rdb := redis.NewFailoverClient(&redis.FailoverOptions{
    MasterName:     redis_master,
    SentinelAddrs:  sentinelAddrs,
    Password:       redis_password,
    DB:             0,
})

// Check connection
rdb.Ping(ctx)
^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

Data Model

Data is typically structured as Go structs, which are then serialized into JSON format for storage in Redis^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. For example, a video struct might contain fields like Id, Title, Description, Imageurl, and Url.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

Create and Update (Saving Data)

To store data, the struct is marshaled into a JSON byte slice^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. The Set method is used to store the data in Redis using a unique key (usually the entity's ID)^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. The process serves as both a Create and Update operation.

func saveVideo(video video)() {
    videoBytes, err := json.Marshal(video)
    if err != nil {
        panic(err)
    }

    err = redisClient.Set(ctx, video.Id, videoBytes, 0).Err()
    if err != nil {
        panic(err)
    }
}
^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

When dealing with a collection, the application iterates over the slice and saves each record individually^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

Read (Retrieving Data)

Retrieving data involves fetching the value from Redis by its key and unmarshaling the JSON back into a Go struct^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

Single Item Retrieval

The Get method retrieves the raw string value, which is then unmarshaled^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

func getVideo(id string)(video video) {
    value, err := redisClient.Get(ctx, id).Result()

    if err != nil {
        panic(err)
    }

    if err != redis.Nil {
        err = json.Unmarshal([]byte(value), &video)
    }

    return video
}
^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

List Retrieval

To retrieve all records (e.g., all videos), the Keys method is used with a wildcard pattern (e.g., "*") to find all relevant keys^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. The application then iterates over these keys, fetching and unmarshaling each record individually^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

func getVideos()(videos []video){
    keys, err := redisClient.Keys(ctx,"*").Result()

    if err != nil {
        panic(err)
    }

    for _, key := range keys {
        video := getVideo(key)
        videos = append(videos, video)
    }

    return videos
}
^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

HTTP Integration

These CRUD operations are commonly exposed via HTTP handlers^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

  • GET Endpoint: A handler can check URL query parameters (e.g., ?id=). If an ID is present, it retrieves a specific item; otherwise, it returns the full list^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].
  • POST/Update Endpoint: A handler accepts a JSON payload, unmarshals it into the struct, and calls the save function^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].
  • [[Go]]
  • [[Redis]]
  • [[Docker]]
  • [[HTTP Handlers]]

Sources

^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]