-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
88 lines (78 loc) · 2.1 KB
/
Copy pathmain.go
File metadata and controls
88 lines (78 loc) · 2.1 KB
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
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"strings"
"syscall"
"time"
"gopkg.d7z.net/cache-proxy/pkg/app"
"gopkg.d7z.net/cache-proxy/pkg/config"
)
const shutdownTimeout = 10 * time.Second
func main() {
level := slog.LevelWarn
switch strings.ToLower(os.Getenv("LOG_LEVEL")) {
case "debug":
level = slog.LevelDebug
case "warn", "warning":
level = slog.LevelWarn
case "error":
level = slog.LevelError
}
debug := os.Getenv("DEBUG") == "true"
if debug && os.Getenv("LOG_LEVEL") == "" {
level = slog.LevelDebug
}
logOptions := &slog.HandlerOptions{Level: level}
if debug {
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, logOptions)))
slog.Debug("debug logging enabled; logs may contain sensitive data")
} else {
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, logOptions)))
}
configPath := flag.String("config", "", "YAML configuration file")
validateOnly := flag.Bool("validate", false, "validate configuration and exit")
flag.Parse()
if *configPath == "" {
_, _ = fmt.Fprintln(os.Stderr, "missing required -config")
os.Exit(2)
}
doc, err := config.LoadFile(*configPath)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := app.Validate(doc); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if *validateOnly {
return
}
runtime, err := app.Open(context.Background(), doc)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := runtime.Start(); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
_ = runtime.Close(shutdownCtx)
cancel()
os.Exit(1)
}
slog.Info("cache proxy started", "bind", doc.Server.Bind, "backend", doc.Server.Backend, "metrics_path", doc.Metrics.Path)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
<-sigs
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
if err := runtime.Close(shutdownCtx); err != nil {
slog.Error("shutdown failed", "err", err)
os.Exit(1)
}
}