Go Connection Examples

The Go Redis driver is an officially recommended driver, and it’s called redigo.

Installation

Installing redigo is simple, using the usual go get procedure:

$ go get github.com/garyburd/redigo/redis

Connecting

To connect via SSL, you will need use Stunnel and use the host and port of your Stunnel connection.

package main

import "github.com/garyburd/redigo/redis"
import "fmt"

func main() {
       //Connect
       c, err := redis.Dial("tcp", "#####.publb.rackspaceclouddb.com:6379")
   if err != nil {
       panic(err)
   }

   response, err := c.Do("AUTH", "YOUR_PASSWORD")

   if err != nil {
       panic(err)
   }

   fmt.Printf("Connected! ", response)
   defer c.Close()
}

Creating, Reading, Updating and Deleting Records

package main

import "github.com/garyburd/redigo/redis"
import "fmt"

func main() {
  c, err := redis.Dial("tcp", "#####.publb.rackspaceclouddb.com:6379")
  if err != nil {
      panic(err)
  }

  response, err := c.Do("AUTH", "YOUR_PASSWORD")

  if err != nil {
      panic(err)
  }

  //Set two keys
  c.Do("SET", "best_car_ever", "Tesla Model S")
  c.Do("SET", "worst_car_ever", "Geo Metro")

  //Get a key
  best_car_ever, err := redis.String(c.Do("GET", "best_car_ever"))
  if err != nil {
      fmt.Println("best_car_ever not found")
      } else {
      //Print our key if it exists
      fmt.Println("best_car_ever exists: " + best_car_ever)
      }

  //Delete a key
  c.Do("DEL", "worst_car_ever")

  //Try to retrieve the key we just deleted
  worst_car_ever, err := redis.String(c.Do("GET", "worst_car_ever"))
  if err != nil {
      fmt.Println("worst_car_ever not found", err)
      } else {
      //Print our key if it exists
      fmt.Println(worst_car_ever)
      }

   defer c.Close()
}

Output from above:

best_car_ever exists: Tesla Model S
worst_car_ever not found redigo: nil returned

Additional reading

If you need more help with redigo, here are some links to more documentation:

As always, if you have any questions, please don’t hesitate to reach out to our support team!