Created
October 25, 2022 21:06
-
-
Save VFUC/e437dfad564916868fd2b7d772b4428a to your computer and use it in GitHub Desktop.
Prometheus wrapper to periodically fetch Kaifu-Lodge visitor numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/json" | |
| "flag" | |
| "fmt" | |
| "io/ioutil" | |
| "log" | |
| "net/http" | |
| "time" | |
| "github.com/prometheus/client_golang/prometheus" | |
| "github.com/prometheus/client_golang/prometheus/promhttp" | |
| ) | |
| func errorOccured(e error) bool { | |
| return e != nil | |
| } | |
| func main() { | |
| var ( | |
| addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.") | |
| checkInterval = flag.Int("check-interval", 60, "The interval to wait between Kaifu API requests") | |
| ) | |
| flag.Parse() | |
| visitors := prometheus.NewGauge( | |
| prometheus.GaugeOpts{ | |
| Name: "visitors", | |
| Help: "Current number of visitors at Kaifu-Lodge", | |
| }, | |
| ) | |
| prometheus.MustRegister(visitors) | |
| go func() { | |
| for { | |
| fmt.Printf("Checking...\n") | |
| visitorNum, err := getCurrentNumberOfVisitors() | |
| if errorOccured(err) { | |
| fmt.Printf("Error while checking... %v\n", err) | |
| } else { | |
| fmt.Printf("New visitor num: %d\n", visitorNum) | |
| visitors.Set(float64(visitorNum)) | |
| } | |
| time.Sleep(time.Duration(*checkInterval) * time.Second) | |
| } | |
| }() | |
| http.Handle("/metrics", promhttp.Handler()) | |
| log.Fatal(http.ListenAndServe(*addr, nil)) | |
| } | |
| func getCurrentNumberOfVisitors() (int32, error) { | |
| client := &http.Client{} | |
| req, err := http.NewRequest("GET", "https://clubconnector.sovd.cloud/api/anwesende/d371bf89-57e5-41d8-9989-440a061157c9-076015/1", nil) | |
| if errorOccured(err) { | |
| return 0, err | |
| } | |
| resp, err := client.Do(req) | |
| if errorOccured(err) { | |
| return 0, err | |
| } | |
| // Read Response Body | |
| respBody, _ := ioutil.ReadAll(resp.Body) | |
| var dat map[string]interface{} | |
| err = json.Unmarshal(respBody, &dat) | |
| if errorOccured(err) { | |
| return 0, err | |
| } | |
| visitors := int32(dat["count"].(float64)) | |
| return visitors, nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment