Skip to content

Instantly share code, notes, and snippets.

@akvanhar
Created Oct 16, 2018
Embed
What would you like to do?
REPL example app with statsd metrics
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"time"
"github.com/etsy/statsd/examples/go"
)
func main() {
br := bufio.NewReader(os.Stdin)
host := "127.0.0.1"
port := 8125
client := statsd.New(host, port)
client.Open()
defer client.Close()
// repl is the read, evaluate, print, loop
for {
if err := readEvaluateProcess(client, br); err != nil {
if err == io.EOF {
return
}
client.Increment("error")
}
}
}
func readEvaluateProcess(client *statsd.StatsdClient, br *bufio.Reader) error {
t1 := time.Now()
client.Increment("service.repl")
fmt.Printf("> ")
line, err := readLine(client, br)
if err != nil {
client.Increment("error")
return err
}
out, err := processLine(client, line)
if err != nil {
client.Increment("error")
return err
}
fmt.Printf("< %s\n\n", out)
t2 := time.Now()
duration := int64(t2.Sub(t1) / time.Millisecond)
client.Timing("stat.timer", duration)
return nil
}
func readLine(client *statsd.StatsdClient, br *bufio.Reader) ([]byte, error) {
line, _, err := br.ReadLine()
client.Increment("service.repl.readLine")
if err != nil {
return nil, err
}
return line, nil
}
func processLine(client *statsd.StatsdClient, in []byte) (out []byte, err error) {
output := bytes.ToUpper(in)
client.Increment("service.repl.processLine")
return output, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment