Skip to main content

Getting Started with Momento Cache in Go

If you need to get going quickly with Go and Momento Cache, this page contains the basic API calls you'll need. Check the Go SDK examples for additional complete, working examples.

Install the Momento SDK

After you have created your Go project, install the Momento Go SDK.

go get github.com/momentohq/client-sdk-go

Set up your API key

You'll need a Momento API key to authenticate with Momento. You can get one from the Momento Web Console. Once you have your token, store it in an environment variable so that the Momento client can consume it:

export MOMENTO_API_KEY=<your Momento token here>

Note: it is best practice to put the token into something like AWS Secret Manager or GCP Secret Manager instead of an environment variable for enhanced security, but we are using one here for demo purposes.

Import libraries and create a CacheClient object

First, pull in the necessary imports and set up the main function.

package main

import (
"context"
"errors"
"log"
"time"

"github.com/google/uuid"
"github.com/momentohq/client-sdk-go/auth"
"github.com/momentohq/client-sdk-go/config"
"github.com/momentohq/client-sdk-go/config/logger"
"github.com/momentohq/client-sdk-go/momento"
"github.com/momentohq/client-sdk-go/responses"
)

func main() {
fmt.Println("Hello, world.")
}

Then instantiate the CacheClient object that will be used to interact with Momento Cache.

context := context.Background()
credentialProvider, err = auth.NewEnvMomentoTokenProvider("MOMENTO_API_KEY")
if err != nil {
panic(err)
}
defaultTtl := 60 * time.Second
eagerConnectTimeout := 30 * time.Second

client, err = momento.NewCacheClientWithEagerConnectTimeout(
config.LaptopLatest(),
credentialProvider,
defaultTtl,
eagerConnectTimeout,
)
if err != nil {
panic(err)
}

client.Ping(context)

Create a new cache in Momento Cache

Use this function to create a new cache in your account.

_, err := client.CreateCache(ctx, &momento.CreateCacheRequest{
CacheName: cacheName,
})
if err != nil {
panic(err)
}

List the names of existing caches in your account

A simple list of the names of caches for the account.

resp, err := client.ListCaches(ctx, &momento.ListCachesRequest{})
if err != nil {
panic(err)
}

switch r := resp.(type) {
case *responses.ListCachesSuccess:
log.Printf("Found caches %+v\n", r.Caches())
}

Write an item to a cache

A simple example of doing a set operation. In the client.set call, the TTL is optional. If you did pass it in, this would override the default TTL value set with the client connection object.

key := uuid.NewString()
value := uuid.NewString()
log.Printf("Setting key: %s, value: %s\n", key, value)
_, err := client.Set(ctx, &momento.SetRequest{
CacheName: cacheName,
Key: momento.String(key),
Value: momento.String(value),
Ttl: time.Duration(9999),
})
if err != nil {
var momentoErr momento.MomentoError
if errors.As(err, &momentoErr) {
if momentoErr.Code() != momento.TimeoutError {
// this would represent a client-side timeout, and you could fall back to your original data source
} else {
panic(err)
}
}
}

Read an item from a cache

This is an example of a simple read operation to get an item from a cache.

key := uuid.NewString()
resp, err := client.Get(ctx, &momento.GetRequest{
CacheName: cacheName,
Key: momento.String(key),
})
if err != nil {
panic(err)
}

switch r := resp.(type) {
case *responses.GetHit:
log.Printf("Lookup resulted in cache HIT. value=%s\n", r.ValueString())
case *responses.GetMiss:
log.Printf("Look up did not find a value key=%s\n", key)
}

Running the code

Use the go run command to execute the code.

go run main.go
info

For more code examples, check out the Momento Go SDK repo.

Beyond these basic API calls check out the API reference page for more information on the full assortment of Momento API calls.