Connect with Go
Establish a connection to the Aiven for Valkey™ service using Go. This example demonstrates how to connect to Aiven for Valkey from Go using the go-valkey/valkey
library, designed to interact with the Valkey protocol.
Variables
Replace placeholders in the code sample with values from your service overview page:
Variable | Description |
---|---|
SERVICE_URI | URI for the Aiven for Valkey service connection |
Prerequisites
Install the valkey-go
library using the following command:
go get github.com/valkey-io/valkey-go
Set up and run
-
Create a file named
main.go
and insert the code below, substituting the placeholder with your Aiven for Valkey URI:package main
import (
"context"
"fmt"
"github.com/valkey-io/valkey-go"
)
var ctx = context.Background()
func main() {
valkeyURI := "SERVICE_URI"
client, err := valkey.NewClient(valkey.ClientOption{InitAddress: []string{valkeyURI}})
if err != nil {
panic(err)
}
defer client.Close()
err = client.Do(ctx, client.B().Set().Key("key").Value("hello world").Nx().Build()).Error()
if err != nil {
panic(err)
}
value, err := client.Do(ctx, client.B().Get().Key("key").Build()).ToString()
if err != nil {
panic(err)
}
fmt.Println("The value of key is:", value)
}This code creates a key named
key
with the valuehello world
without an expiration. It then retrieves this key from the Valkey service and outputs its value. -
Run the script using the following command:
go run main.go
A successful connection displays:
The value of key is: hello world
Related pages
- For additional information, see valkey-go github repository.