A newer version of this documentation is available.

View Latest

Managing Connections Using the Go SDK with Couchbase Server

This section describes how to connect the Go SDK to a Couchbase cluster and bucket. It contains best practices as well as information on the connection string, SSL and other advanced connection options.

Creating a Cluster Object

The Cluster object serves as an organizational unit for any Bucket objects created. As on the server each bucket is a member of a cluster, likewise in the SDK each Bucket object is a child of a Cluster. To create a cluster, construct it using a connection string, specifying the scheme and host(s) to connect to gocb.Connect:

cluster, err := gocb.Connect("couchbase://localhost")

You can also specify multiple hosts in the connection string by separating each host with a comma:

cluster, err := gocb.Connect("couchbase://host1,host2,host3,hostN")

Specifying multiple hosts may add additional redundancy when bootstrapping.

Opening a Bucket

Once the Cluster object has been created, you may open one or more Bucket objects using Cluster.OpenBucket. The first argument is the bucket name to use, and the second is the bucket password - which should be provided if the bucket is password protected, or supplied as nil otherwise.

bucket1, err := cluster.OpenBucket("messages", nil)
protectedBucket, err := cluster.openBucket("protected", "s3cr3t")

Note that the bucket password is not the administrative password used to access the Couchbase Web UI.

Once the bucket has been created, it may be used throughout your application. Buckets are thread-safe and need not be locked or otherwise protected to be used from multiple threads.

You should only need to open one Bucket object for each Couchbase Bucket in your application, and you should attempt to keep the Bucket object available and open for as long as you plan to access Couchbase within your application.

Closing a Bucket

When your application is done talking to Couchbase, you can issue the Bucket.Close() call on the bucket, which will disconnect your application from the given bucket.

Configuring SSL

SSL Verification not implemented in Go SDK
Be aware that the Go SDK does not implement certificate validation when connecting to Couchbase using SSL. This means that SSL connections are subject to man-in-the-middle attacks.

To configure SSL, pass an SSL scheme with your connection string when creating your cluster object.

myCluster, _ := gocb.Connect("couchbases://")
myBucket, _ := myCluster.OpenBucket("default", "")