Skip to content

Instantly share code, notes, and snippets.

@DazWilkin
Created June 28, 2019 17:13
Show Gist options
  • Save DazWilkin/6dc095eb087253eea65342d05c1bd697 to your computer and use it in GitHub Desktop.
Save DazWilkin/6dc095eb087253eea65342d05c1bd697 to your computer and use it in GitHub Desktop.
Particle, Cloud Functions & Prometheus
package q
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/push"
)
type data struct {
Event string `json:"event"`
Data string `json:"data"`
Published string `json:"published_at"`
CoreID string `json:"coreid"`
}
// ToPushGateway marshals then sends a particle.io webhook event to a Prometheus PushGateway
func ToPushGateway(w http.ResponseWriter, r *http.Request) {
log.Println("function")
gateway := os.Getenv("GATEWAY")
if gateway == "" {
log.Fatal("No Prometheus PushGateway defined")
}
var d data
if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
fmt.Fprint(w, err)
return
}
percentGauge := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "percent",
Help: "The percentage humidity.",
})
percent, err := strconv.ParseFloat(d.Data, 64)
if err != nil {
log.Fatal(err)
}
log.Printf("value: %f", percent)
percentGauge.Set(percent)
if err := push.New(fmt.Sprintf("http://%s", gateway), "pushgateway").
Collector(percentGauge).
Grouping("core_id", d.CoreID).
Push(); err != nil {
log.Print(err)
}
fmt.Fprint(w, "ok")
}
module cloudfunction
go 1.12
require github.com/prometheus/client_golang v1.0.0 // indirect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment