Skip to content

Commit a41fca8

Browse files
andreiavrammsdbradfitz
authored andcommitted
Add Ping method. (bradfitz#91)
* Add Ping method.
1 parent 551aad2 commit a41fca8

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

memcache/memcache.go

+31
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ var (
112112
resultTouched = []byte("TOUCHED\r\n")
113113

114114
resultClientErrorPrefix = []byte("CLIENT_ERROR ")
115+
versionPrefix = []byte("VERSION")
115116
)
116117

117118
// New returns a memcache client using the provided server(s)
@@ -398,6 +399,30 @@ func (c *Client) flushAllFromAddr(addr net.Addr) error {
398399
})
399400
}
400401

402+
// ping sends the version command to the given addr
403+
func (c *Client) ping(addr net.Addr) error {
404+
return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
405+
if _, err := fmt.Fprintf(rw, "version\r\n"); err != nil {
406+
return err
407+
}
408+
if err := rw.Flush(); err != nil {
409+
return err
410+
}
411+
line, err := rw.ReadSlice('\n')
412+
if err != nil {
413+
return err
414+
}
415+
416+
switch {
417+
case bytes.HasPrefix(line, versionPrefix):
418+
break
419+
default:
420+
return fmt.Errorf("memcache: unexpected response line from ping: %q", string(line))
421+
}
422+
return nil
423+
})
424+
}
425+
401426
func (c *Client) touchFromAddr(addr net.Addr, keys []string, expiration int32) error {
402427
return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
403428
for _, key := range keys {
@@ -644,6 +669,12 @@ func (c *Client) DeleteAll() error {
644669
})
645670
}
646671

672+
// Ping checks all instances if they are alive. Returns error if any
673+
// of them is down.
674+
func (c *Client) Ping() error {
675+
return c.selector.Each(c.ping)
676+
}
677+
647678
// Increment atomically increments key by delta. The return value is
648679
// the new value after being incremented or an error. If the value
649680
// didn't exist in memcached the error is ErrCacheMiss. The value in

memcache/memcache_test.go

+3
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,9 @@ func testWithClient(t *testing.T, c *Client) {
209209
t.Errorf("post-DeleteAll want ErrCacheMiss, got %v", err)
210210
}
211211

212+
// Test Ping
213+
err = c.Ping()
214+
checkErr(err, "error ping: %s", err)
212215
}
213216

214217
func testTouchWithClient(t *testing.T, c *Client) {

0 commit comments

Comments
 (0)