Saturday, September 5, 2015

Connecting to redis on heroku with golang

I have an app on heroku using the redis-addon provided by heroku ("Redis Heroku"). To connect to this instance using go-redis, I have found this to be a working solution:
  • The redis url is provided as an environment variable, REDIS_URL
  • To use redis from golang, I use redis-go.  I install this library by typing "go get github.com/gopkg.in/redis.v3"
  • Parse the url and extract the user before connecting(unless, you might end up with the error "dial tcp: too many colons in address redis://...")
import "gopkg.in/redis.v3"
var (
//Client for the database connection
client *redis.Client
)
func connect() {
var resolvedURL = os.Getenv("REDIS_URL")
var password = ""
if !strings.Contains(herokuURL, "localhost") {
parsedURL, _ := url.Parse(herokuURL)
password, _ = parsedURL.User.Password()
resolvedURL = parsedURL.Host
}
fmt.Printf("connecting to %s", herokuURL)
client = redis.NewClient(&redis.Options{
Addr: resolvedURL,
Password: password,
DB: 0, // use default DB
})
}
view raw golang_redis.go hosted with ❤ by GitHub

No comments:

Post a Comment