-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (68 loc) · 1.83 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
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"time"
"github.com/heptiolabs/healthcheck"
"github.com/m1ome/magnify/pkg"
)
var configPath string
func init() {
flag.StringVar(&configPath, "c", "config.yaml", "yaml file config path")
flag.Parse()
}
func main() {
cfg, err := pkg.NewConfig(configPath)
if err != nil {
log.Fatalf("error initialzing config: %v", err)
}
log.Print("scraping metrics on a startup")
cache := pkg.NewCache(time.Second * time.Duration(cfg.Cache.Expiration))
metrics, err := pkg.NewMetrics(cfg, cache)
if err != nil {
log.Fatalf("error initializing metrics: %v", err)
}
runUpdate(metrics)
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
sendResponse(cache.Copy(), w)
})
http.HandleFunc("/key/{name}", func(w http.ResponseWriter, req *http.Request) {
v, ok := cache.Load(req.PathValue("name"))
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
sendResponse(v, w)
})
health := healthcheck.NewHandler()
http.HandleFunc("/health/live", health.LiveEndpoint)
http.HandleFunc("/health/ready", health.ReadyEndpoint)
log.Printf("starting listening http server on %s", cfg.Http.Addr)
if err := http.ListenAndServe(cfg.Http.Addr, nil); err != nil {
log.Fatalf("error listing on '%s': %v", cfg.Http.Addr, err)
}
}
func sendResponse(v any, w http.ResponseWriter) {
buf, err := json.Marshal(v)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
w.Write(buf)
}
func runUpdate(metrics *pkg.Metrics) {
if err := metrics.Update(); err != nil {
log.Fatalf("error updating metrics: %v", err)
}
go func() {
ticker := time.NewTicker(time.Minute)
for range ticker.C {
if err := metrics.Update(); err != nil {
log.Printf("error updating metrics: %v", err)
}
}
}()
}