bug fixes and refactoring

This commit is contained in:
David Norton
2017-10-03 09:04:29 -04:00
parent d7b88b10ad
commit 6aee40fac1
4 changed files with 90 additions and 92 deletions

View File

@@ -2,14 +2,40 @@ package particle
import (
"encoding/json"
"github.com/gorilla/mux"
"github.com/influxdata/telegraf"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/influxdata/telegraf"
)
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)
}
type ParticleWebhook struct {
Path string
acc telegraf.Accumulator
@@ -23,26 +49,19 @@ func (rb *ParticleWebhook) Register(router *mux.Router, acc telegraf.Accumulator
func (rb *ParticleWebhook) eventHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
e := newEvent()
if err := json.NewDecoder(r.Body).Decode(e); err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
pTime, err := e.Time()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
dummy := &DummyData{}
if err := json.Unmarshal(data, dummy); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
pd := &ParticleData{}
if err := json.Unmarshal([]byte(dummy.Data), pd); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
pTime, err := dummy.Time()
if err != nil {
log.Printf("Time Conversion Error")
pTime = time.Now()
log.Printf("error parsing particle event time: %s. Using telegraf host time instead: %s", e.PublishedAt, pTime)
}
rb.acc.AddFields(dummy.InfluxDB, pd.Fields, pd.Tags, pTime)
rb.acc.AddFields(e.Name, e.Data.Fields, e.Data.Tags, pTime)
w.WriteHeader(http.StatusOK)
}