Installation & Connections

Getting started with Redigo involves installing the package and establishing a connection to your Redis server. This guide covers both steps in detail.

Installation

Install the Redigo package using the go get command. Redigo requires Go version 1.17 or later.

go get github.com/gomodule/redigo/redis

The Go distribution is Redigo's only dependency.

Establishing a Connection

Redigo provides several functions to connect to a Redis server, offering fine-grained control over connection parameters.

Basic Connection

The simplest way to connect is with redis.Dial. It takes the network type and address as arguments.

conn, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
    // handle error
}
defer conn.Close()

Connecting with a URL

You can also connect using a Redis URL with redis.DialURL. The URL scheme is compatible with the IANA specification for Redis URIs.

// Example URL: redis://:password@hostname:port/database_number
conn, err := redis.DialURL("redis://:mysecret@localhost:6379/0")
if err != nil {
    // handle error
}
defer conn.Close()

The DialURL function automatically handles authentication and database selection based on the URL components.

Connection Options

For more control, you can pass DialOption arguments to the Dial or DialURL functions. This is the recommended way to configure timeouts, authentication, and other settings.

Here are some of the most common options:

  • DialConnectTimeout(d time.Duration): Specifies the timeout for establishing the connection.
  • DialReadTimeout(d time.Duration): Sets the timeout for waiting for a reply.
  • DialWriteTimeout(d time.Duration): Sets the timeout for writing a command.
  • DialDatabase(db int): Specifies the database to SELECT upon connection.
  • DialPassword(password string): Authenticates with the given password (AUTH password).
  • DialUsername(username string): Specifies the username for ACL authentication (used with DialPassword).
  • DialClientName(name string): Sets the client name with CLIENT SETNAME.
  • DialKeepAlive(d time.Duration): Specifies the keep-alive period for TCP connections.

Example using options:

conn, err := redis.Dial("tcp", "localhost:6379",
    redis.DialConnectTimeout(1*time.Second),
    redis.DialReadTimeout(1*time.Second),
    redis.DialWriteTimeout(1*time.Second),
    redis.DialPassword("your-password"),
    redis.DialDatabase(2),
)
if err != nil {
    // handle error
}
defer conn.Close()

TLS Connections

To connect to a Redis server over TLS, use the DialUseTLS option or the rediss:// URL scheme.

Using DialUseTLS:

conn, err := redis.Dial("tcp", "your-redis-host:6380",
    redis.DialUseTLS(true),
    redis.DialTLSSkipVerify(true), // Use this for self-signed certs, not for production
)

Using a URL:

conn, err := redis.DialURL("rediss://user:password@your-redis-host:6380/0")

For custom TLS configurations, you can provide your own *tls.Config with the DialTLSConfig option.