Develop Go Apps

Prerequisites

This tutorial assumes that you have:

  • installed YugabyteDB, created a universe and are able to interact with it using the Redis shell. If not, please follow these steps in Quick start.
  • installed Go version 1.8+

Install the Go Redis driver

To install the driver, locally run the following go get command.

  1. $ go get github.com/go-redis/redis

Writing a HelloWorld Redis application

Create a file ybredis_hello_world.go and copy the contents below.

  1. package main;
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/go-redis/redis"
  6. )
  7. func main() {
  8. // Connect to the cluster.
  9. client := redis.NewClient(&redis.Options{
  10. Addr: "localhost:6379",
  11. Password: "", // no password set
  12. DB: 0, // use the default DB
  13. })
  14. defer client.Close()
  15. // Insert some data (for user id 1).
  16. var userid string = "1"
  17. ok, err := client.HMSet(userid, map[string]interface{}{
  18. "name": "John",
  19. "age": "35",
  20. "language": "Redis"}).Result()
  21. if (err != nil) {
  22. log.Fatal(err)
  23. }
  24. fmt.Printf("HMSET returned '%s' for id=%s with values: name=John, age=35, language=Redis\n", ok, userid)
  25. // Query the data.
  26. result, err := client.HGetAll("1").Result()
  27. fmt.Printf("Query result for id=%s: '%v'\n", userid, result)
  28. }

Running the application

To execute the file, run the following command.

  1. $ go run ybredis_hello_world.go

You should see the following as the output.

  1. HMSET returned 'OK' for id=1 with values: name=John, age=35, language=Redis
  2. Query result for id=1: 'map[age:35 language:Redis name:John]'