receiver.go 978 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
package statsd

import (
	"log"
	"net"
)

const DefaultMetricsAddr = ":8125"

type Handler func(Metric)

type MetricReceiver struct {
	Addr    string  // UDP address on which to listen for metrics
	Handler Handler // handler to invoke
}

func (r *MetricReceiver) ListenAndReceive() error {
	addr := r.Addr
	if addr == "" {
		addr = DefaultMetricsAddr
	}
	c, err := net.ListenPacket("udp", addr)
	if err != nil {
		return err
	}
	return r.Receive(c)
}

func (r *MetricReceiver) Receive(c net.PacketConn) error {
	defer c.Close()

	msg := make([]byte, 1024)
	for {
		nbytes, _, err := c.ReadFrom(msg)
		if err != nil {
			log.Printf("%s", err)
			continue
		}
		log.Printf("%s", msg[:nbytes])
		go r.handleMessage(msg[:nbytes])
	}
	panic("not reached")
}

func (srv *MetricReceiver) handleMessage(msg []byte) {
	metrics, err := parseMessage(string(msg))
	if err != nil {
		log.Printf("Error parsing metric %s", err)
	}
	for _, metric := range metrics {
		srv.Handler(metric)
	}
}