Skip to content
This repository has been archived by the owner on Sep 28, 2022. It is now read-only.

Commit

Permalink
convenience method for creating new cluster from string slice
Browse files Browse the repository at this point in the history
Creating a client against a cluster is a bit verbose without this.
  • Loading branch information
Matt Jaffee committed Jun 30, 2017
1 parent 0a28916 commit c76e1e2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
17 changes: 17 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,23 @@ func NewClientWithURI(uri *URI) *Client {
return NewClientWithCluster(NewClusterWithHost(uri), nil)
}

// NewClientFromAddresses creates a client for a cluster specified by `hosts`. Each
// string in `hosts` is the string represenation of a URI. E.G
// node0.pilosa.com:10101
func NewClientFromAddresses(addresses []string, options *ClientOptions) (*Client, error) {
uris := make([]*URI, len(addresses))
for i, address := range addresses {
uri, err := NewURIFromAddress(address)
if err != nil {
return nil, err
}
uris[i] = uri
}
cluster := NewClusterWithHost(uris...)
client := NewClientWithCluster(cluster, options)
return client, nil
}

// NewClientWithCluster creates a client with the given cluster and options.
// Pass nil for default options.
func NewClientWithCluster(cluster *Cluster, options *ClientOptions) *Client {
Expand Down
38 changes: 38 additions & 0 deletions client_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package pilosa

import (
"reflect"
"testing"
)

func TestNewClientFromAddresses(t *testing.T) {
cli, err := NewClientFromAddresses([]string{":10101", "node0.pilosa.com:10101", "node2.pilosa.com"}, &ClientOptions{})

if err != nil {
t.Fatalf("Creating client from addresses: %v", err)
}
expectedHosts := []URI{
{scheme: "http", port: 10101, host: "localhost"},
{scheme: "http", port: 10101, host: "node0.pilosa.com"},
{scheme: "http", port: 10101, host: "node2.pilosa.com"},
}
actualHosts := cli.cluster.Hosts()
if !reflect.DeepEqual(actualHosts, expectedHosts) {
t.Fatalf("Unexpected hosts in client's cluster, got: %v, expected: %v", actualHosts, expectedHosts)
}

cli, err = NewClientFromAddresses([]string{"://"}, &ClientOptions{})
if err == nil {
t.Fatalf("Did not get expected error when creating client: %v", cli.cluster.Hosts())
}

cli, err = NewClientFromAddresses([]string{}, &ClientOptions{})
if err != nil {
t.Fatalf("Got error when creating empty client from addresses: %v", err)
}

cli, err = NewClientFromAddresses(nil, &ClientOptions{})
if err != nil {
t.Fatalf("Got error when creating empty client from addresses: %v", err)
}
}

0 comments on commit c76e1e2

Please sign in to comment.