telegraf/plugins/inputs/webhooks/particle/particle_webhooks.go

68 lines
1.5 KiB
Go
Raw Normal View History

2017-10-02 20:50:23 +00:00
package particle
import (
"encoding/json"
"log"
"net/http"
"time"
2017-10-03 13:04:29 +00:00
"github.com/gorilla/mux"
"github.com/influxdata/telegraf"
2017-10-02 20:50:23 +00:00
)
2017-10-03 13:04:29 +00:00
type event struct {
Name string `json:"event"`
Data data `json:"data"`
TTL int `json:"ttl"`
PublishedAt string `json:"published_at"`
Database string `json:"influx_db"`
}
type data struct {
Tags map[string]string `json:"tags"`
Fields map[string]interface{} `json:"values"`
}
func newEvent() *event {
return &event{
Data: data{
Tags: make(map[string]string),
Fields: make(map[string]interface{}),
},
}
}
func (e *event) Time() (time.Time, error) {
return time.Parse("2006-01-02T15:04:05Z", e.PublishedAt)
}
2017-10-02 20:50:23 +00:00
type ParticleWebhook struct {
Path string
acc telegraf.Accumulator
}
func (rb *ParticleWebhook) Register(router *mux.Router, acc telegraf.Accumulator) {
router.HandleFunc(rb.Path, rb.eventHandler).Methods("POST")
log.Printf("I! Started the webhooks_particle on %s\n", rb.Path)
rb.acc = acc
}
func (rb *ParticleWebhook) eventHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
2017-10-03 13:04:29 +00:00
e := newEvent()
if err := json.NewDecoder(r.Body).Decode(e); err != nil {
log.Println(err)
2017-10-02 20:50:23 +00:00
w.WriteHeader(http.StatusBadRequest)
return
}
2017-10-03 13:04:29 +00:00
pTime, err := e.Time()
2017-10-02 20:50:23 +00:00
if err != nil {
pTime = time.Now()
2017-10-03 13:04:29 +00:00
log.Printf("error parsing particle event time: %s. Using telegraf host time instead: %s", e.PublishedAt, pTime)
2017-10-02 20:50:23 +00:00
}
2017-10-03 13:04:29 +00:00
rb.acc.AddFields(e.Name, e.Data.Fields, e.Data.Tags, pTime)
2017-10-02 20:50:23 +00:00
w.WriteHeader(http.StatusOK)
}