-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (86 loc) · 2.29 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const Namespace = "helloworld"
const WeatherStation = "KBOS" // Boston Logan Airport
type WeatherResponse struct {
Properties struct {
Temperature struct {
Value float64 `json:"value"`
} `json:"temperature"`
} `json:"properties"`
}
type metrics struct {
temperature *prometheus.GaugeVec
queries *prometheus.CounterVec
}
func getWeather() (float64, error) {
url := fmt.Sprintf("https://api.weather.gov/stations/%s/observations/latest", WeatherStation)
httpClient := &http.Client{Timeout: time.Second * 30}
res, err := httpClient.Get(url)
if err != nil {
log.Printf("ERROR: Could not fetch %s", url)
return 0, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
var weather WeatherResponse
err = json.Unmarshal(body, &weather)
if err != nil {
log.Println("ERROR: Could not unmarshal json")
return 0, err
}
temperature := weather.Properties.Temperature.Value
return temperature, nil
}
func RegisterMetrics(reg prometheus.Registerer) *metrics {
m := &metrics{
temperature: prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: Namespace,
Name: "outdoor_temperature_celsius",
Help: "Outdoor temperature reported by the NWS.",
},
[]string{"station"},
),
queries: prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Name: "nws_query_attempts_total",
Help: "Number of times we've queried the NWS API.",
},
[]string{"station"},
),
}
reg.MustRegister(m.temperature)
reg.MustRegister(m.queries)
return m
}
func main() {
reg := prometheus.NewRegistry()
m := RegisterMetrics(reg)
go func() {
for {
temperature, err := getWeather()
m.queries.With(prometheus.Labels{"station": WeatherStation}).Inc()
if err != nil {
log.Print(err)
log.Println("Not updating metrics on this run.")
time.Sleep(time.Minute * 1)
continue
}
m.temperature.With(prometheus.Labels{"station": WeatherStation}).Set(temperature)
time.Sleep(time.Minute * 5)
}
}()
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{Registry: reg}))
log.Fatal(http.ListenAndServe(":23456", nil))
}