/
sendgrid-statsd.go
71 lines (58 loc) · 1.58 KB
/
sendgrid-statsd.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"fmt"
"log"
"flag"
"time"
"bytes"
"net/http"
"encoding/json"
"github.com/rakyll/globalconf"
"github.com/cactus/go-statsd-client/statsd"
)
func main() {
log.Print("Starting sendgrid webhook endpoint...")
statsdHost := flag.String("statsd_host", "127.0.0.1:8125", "")
statsdClientName := flag.String("client_name", "sendgrid", "")
conf, err := globalconf.New("sendgridstatsd")
conf.ParseAll()
log.Printf("Sending to statdsd host: %+v", *statsdHost)
// first create a client
client, err := statsd.New(*statsdHost, *statsdClientName)
// handle any errors
if err != nil {
log.Fatal(err)
}
// make sure to clean up
defer client.Close()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
handler(w, r, client)
})
log.Print("done\n")
http.ListenAndServe(":9090", nil)
}
func handler(w http.ResponseWriter, r *http.Request, client *statsd.Client) {
if (r.Method != "POST") {
log.Fatal("Expected POST request")
}
fmt.Fprintf(w, "Thanks!")
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
var ec []map[string]interface{}
if err := json.Unmarshal(buf.Bytes(), &ec); err != nil {
log.Fatal(err)
}
for _, item := range ec {
err := client.Inc("mail.event_type." + item["event"].(string), 1, 1.0)
// handle any errors
if err != nil {
log.Fatalf("Error sending metric: %+v", err)
}
err = client.Inc("mail.event", 1, 1.0)
// handle any errors
if err != nil {
log.Fatalf("Error sending metric: %+v", err)
}
log.Printf("%s(%s): %s\n", item["email"], time.Unix(int64(item["timestamp"].(float64)), 0), item["event"])
}
}