-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
65 lines (55 loc) · 1.58 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
package main
import (
"log/slog"
"net/http"
"os"
"strings"
"github.com/chpc-uofu/cgroup-warden/control"
"github.com/chpc-uofu/cgroup-warden/metrics"
)
func authorize(next http.Handler, secret string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+secret {
slog.Warn("unauthorized request", "address", r.RemoteAddr)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func updateLogLevel(level string) {
var slogLevel slog.Level = slog.LevelInfo
switch strings.ToLower(level) {
case "debug":
slogLevel = slog.LevelDebug
case "info":
slogLevel = slog.LevelInfo
case "warning":
slogLevel = slog.LevelWarn
case "error":
slogLevel = slog.LevelError
}
slog.SetLogLoggerLevel(slogLevel)
}
func main() {
conf, err := NewConfig()
if err != nil {
slog.Error("Unable to parse configuration", "err", err)
os.Exit(1)
}
updateLogLevel(conf.LogLevel)
mux := http.NewServeMux()
mux.Handle("/metrics", metrics.MetricsHandler(conf.RootCGroup, conf.MetaMetrics))
mux.Handle("/", http.NotFoundHandler())
if conf.InsecureMode {
mux.Handle("/control", control.ControlHandler)
slog.Info("Starting server")
slog.Error("server error", "err", http.ListenAndServe(conf.ListenAddress, mux))
os.Exit(1)
} else {
mux.Handle("/control", authorize(control.ControlHandler, conf.BearerToken))
slog.Info("Starting server")
slog.Error("server error", "err", http.ListenAndServeTLS(conf.ListenAddress, conf.Certificate, conf.PrivateKey, mux))
os.Exit(1)
}
}