Skip to content

Instantly share code, notes, and snippets.

@schigh
Created March 28, 2019 22:20
Show Gist options
  • Save schigh/4e321d0b28bd69f58d55d79ecd2d5b6a to your computer and use it in GitHub Desktop.
Save schigh/4e321d0b28bd69f58d55d79ecd2d5b6a to your computer and use it in GitHub Desktop.
Simple UDP packet catcher and displayer for DataDog statsd stats
package main
import (
"bytes"
"log"
"net"
"strings"
"time"
)
func main() {
// listen to incoming udp packets
pc, err := net.ListenPacket("udp", ":8130")
if err != nil {
log.Fatal(err)
}
defer pc.Close()
for {
buf := make([]byte, 2048)
pc.ReadFrom(buf)
parselines(buf)
}
}
func parselines(b []byte) {
lines := bytes.Split(b, []byte{'\n'})
for _, l := range lines {
parseline(l)
}
}
func parseline(b []byte) {
parts := bytes.Split(b, []byte{'|', 'h', '|', '#'})
if len(parts) == 0 {
return
}
if len(parts) == 1 {
showStat(parts[0], []byte{})
return
}
showStat(parts[0], parts[1])
}
func showStat(h, b []byte) {
sb := strings.Builder{}
sb.WriteString(time.Now().Format(time.StampMicro) + "\n")
sb.Write(h)
s := bytes.Split(b, []byte{','})
for i := 0; i < len(s); i++ {
sb.Write([]byte{'\n', '\t'})
sb.Write(s[i])
}
sb.WriteByte('\n')
println(sb.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment