diff --git a/README.md b/README.md index 350c4d0a..17161caa 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ import ( ) func main() { - mc := memcache.New("10.0.0.1:11211", "10.0.0.2:11211", "10.0.0.3:11212") + mc, err := memcache.New("10.0.0.1:11211", "10.0.0.2:11211", "10.0.0.3:11212") mc.Set(&memcache.Item{Key: "foo", Value: []byte("my value")}) it, err := mc.Get("foo") diff --git a/memcache/memcache.go b/memcache/memcache.go index b2ebacd2..f79d4463 100644 --- a/memcache/memcache.go +++ b/memcache/memcache.go @@ -118,10 +118,13 @@ var ( // New returns a memcache client using the provided server(s) // with equal weight. If a server is listed multiple times, // it gets a proportional amount of weight. -func New(server ...string) *Client { +// Error is returned if any of the server names fail to resolve. +// No attempt is made to connect to the server. If any error +// is returned, no changes are made to the ServerList. +func New(server ...string) (*Client, error) { ss := new(ServerList) - ss.SetServers(server...) - return NewFromSelector(ss) + err := ss.SetServers(server...) + return NewFromSelector(ss), err } // NewFromSelector returns a new Client using the provided ServerSelector. diff --git a/memcache/memcache_test.go b/memcache/memcache_test.go index 4b60a15d..0238c34b 100644 --- a/memcache/memcache_test.go +++ b/memcache/memcache_test.go @@ -48,8 +48,11 @@ func TestLocalhost(t *testing.T) { } io.WriteString(c, "flush_all\r\n") c.Close() - - testWithClient(t, New(localhostTCPAddr)) + client, err := New(localhostTCPAddr) + if err != nil { + t.Fatalf("error creating client: %v", err) + } + testWithClient(t, client) } // Run the memcached binary as a child process and connect to its unix socket. @@ -71,8 +74,11 @@ func TestUnixSocket(t *testing.T) { } time.Sleep(time.Duration(25*i) * time.Millisecond) } - - testWithClient(t, New(sock)) + client, err := New(sock) + if err != nil { + t.Fatalf("error creating client: %v", err) + } + testWithClient(t, client) } func TestFakeServer(t *testing.T) { @@ -86,7 +92,11 @@ func TestFakeServer(t *testing.T) { srv := &testServer{} go srv.Serve(ln) - testWithClient(t, New(ln.Addr().String())) + client, err := New(ln.Addr().String()) + if err != nil { + t.Fatalf("error creating client: %v", err) + } + testWithClient(t, client) } func TestTLS(t *testing.T) { @@ -148,7 +158,7 @@ func TestTLS(t *testing.T) { time.Sleep(time.Duration(25*i) * time.Millisecond) } - c := New(net.JoinHostPort("127.0.0.1", strconv.Itoa(port))) + c, err := New(net.JoinHostPort("127.0.0.1", strconv.Itoa(port))) c.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { var td tls.Dialer td.Config = &tls.Config{ @@ -412,7 +422,7 @@ func BenchmarkOnItem(b *testing.B) { }() addr := fakeServer.Addr() - c := New(addr.String()) + c, err := New(addr.String()) if _, err := c.getConn(addr); err != nil { b.Fatal("failed to initialize connection to fake server") }