covid-exporter/main.go

134 lines
2.9 KiB
Go

// vi:ts=4:sts=4:sw=4:noet:tw=72
//
// covid-exporter
//
// Copyright (c) 2021 Andreas Neue <an@dnix.de>
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type CovidRecord struct {
Updated int
Country string
CountryInfo interface{}
Cases int
TodayCases int
Deaths int
TodayDeaths int
Recovered int
TodayRecovered int
Active int
Critical int
CasesPerOneMillion float32
DeathsPerOneMillion float32
Tests int
TestsPerOneMillion int
Population int
Continent string
OneCasePerPeople int
OneDeathPerPeople int
OneTestPerPeople int
ActivePerOneMillion float32
RecoveredPerOneMillion float32
CriticalPerOneMillion float32
}
var (
gaugeCases *prometheus.GaugeVec
gaugeActive *prometheus.GaugeVec
gaugeCritical *prometheus.GaugeVec
gaugePopulation *prometheus.GaugeVec
)
func main() {
url := "https://corona.lmao.ninja/v3/covid-19/countries"
go getCovidStats(url)
serveMetrics()
}
func getCovidStats(url string) {
for {
resp, err := http.Get(url)
if err != nil {
fmt.Printf("%v\n", err)
continue
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%v\n", err)
continue
}
var cr []CovidRecord
err = json.Unmarshal(data, &cr)
if err != nil {
fmt.Printf("%v\n", err)
continue
}
for i := range cr {
gaugeCases.WithLabelValues(cr[i].Country).Set(float64(cr[i].Cases))
gaugeActive.WithLabelValues(cr[i].Country).Set(float64(cr[i].Active))
gaugeCritical.WithLabelValues(cr[i].Country).Set(float64(cr[i].Critical))
gaugePopulation.WithLabelValues(cr[i].Country).Set(float64(cr[i].Population))
}
time.Sleep(15 * time.Minute)
}
}
func serveMetrics() {
gaugeCases = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "covid_cases",
Help: "Covid-19 cases",
},
[]string{
"country",
},
)
prometheus.MustRegister(gaugeCases)
gaugeActive = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "covid_active",
Help: "Covid-19 active cases",
},
[]string{
"country",
},
)
prometheus.MustRegister(gaugeActive)
gaugeCritical = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "covid_critical",
Help: "Covid-19 critical cases",
},
[]string{
"country",
},
)
prometheus.MustRegister(gaugeCritical)
gaugePopulation = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "covid_population",
Help: "Population",
},
[]string{
"country",
},
)
prometheus.MustRegister(gaugePopulation)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":9099", nil)
}