Skip to content

Instantly share code, notes, and snippets.

@groundwalker
Created January 14, 2016 14:43
Show Gist options
  • Save groundwalker/5412c0562395b5b461ad to your computer and use it in GitHub Desktop.
Save groundwalker/5412c0562395b5b461ad to your computer and use it in GitHub Desktop.
get STATS of memcached
package main
import (
"fmt"
"net" // https://golang.org/pkg/net/
"bufio"
"regexp"
"strings"
"os"
)
type Connection struct {
conn net.Conn
buf bufio.ReadWriter
}
func Connect(ipaddr string, port string) (conn *Connection, err error) {
nc, err := net.Dial("tcp", ipaddr+":"+port)
if err != nil {
return nil, err
}
err = nil
return &Connection{
conn: nc,
buf: bufio.ReadWriter{
Reader: bufio.NewReader(nc),
Writer: bufio.NewWriter(nc),
},
}, err
}
func main() {
ipaddr := os.Args[1]
// connect to a Memcached server
conn, err := Connect(ipaddr, "11211")
if err != nil {
panic(err)
}
defer conn.conn.Close()
// send "stats" command
conn.buf.WriteString("stats\r\n")
conn.buf.Flush()
re := regexp.MustCompile("^STAT (.*) ([0-9]+)$")
stats := map[string]string{}
for {
bl, _, _ := conn.buf.ReadLine()
l := string(bl)
if strings.HasPrefix(l, "END") {
break
}
if strings.Contains(l, "ERROR") {
panic("ERROR")
}
// get value of each STAT
mc := re.FindStringSubmatch(l)
if len(mc) > 2 {
stats[mc[1]] = mc[2]
}
}
fmt.Printf("%#v\n", stats)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment