-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
113 lines (96 loc) · 2.52 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
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/database64128/proxy-sharing-go/jsonhelper"
"github.com/database64128/proxy-sharing-go/logging"
"github.com/database64128/proxy-sharing-go/service"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
testConf bool
confPath string
zapConf string
logLevel zapcore.Level
)
func init() {
flag.BoolVar(&testConf, "testConf", false, "Test the configuration file without starting the services")
flag.StringVar(&confPath, "confPath", "", "Path to JSON configuration file")
flag.StringVar(&zapConf, "zapConf", "", "Preset name or path to JSON configuration file for building the zap logger.\nAvailable presets: console (default), systemd, production, development")
flag.TextVar(&logLevel, "logLevel", zapcore.InvalidLevel, "Override the logger configuration's log level.\nAvailable levels: debug, info, warn, error, dpanic, panic, fatal")
}
func main() {
flag.Parse()
if confPath == "" {
fmt.Println("Missing -confPath <path>.")
flag.Usage()
os.Exit(1)
}
var (
zc zap.Config
sc service.Config
)
switch zapConf {
case "console", "":
zc = logging.NewProductionConsoleConfig(false)
case "systemd":
zc = logging.NewProductionConsoleConfig(true)
case "production":
zc = zap.NewProductionConfig()
case "development":
zc = zap.NewDevelopmentConfig()
default:
if err := jsonhelper.OpenAndDecodeDisallowUnknownFields(zapConf, &zc); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
if logLevel != zapcore.InvalidLevel {
zc.Level.SetLevel(logLevel)
}
logger, err := zc.Build()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer logger.Sync()
if err = jsonhelper.OpenAndDecodeDisallowUnknownFields(confPath, &sc); err != nil {
logger.Fatal("Failed to load config",
zap.String("confPath", confPath),
zap.Error(err),
)
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
sig := <-sigCh
logger.Info("Received exit signal", zap.Stringer("signal", sig))
cancel()
}()
m, err := sc.Manager(ctx, logger)
if err != nil {
logger.Fatal("Failed to create service manager",
zap.String("confPath", confPath),
zap.Error(err),
)
}
defer m.Close()
if testConf {
logger.Info("Config test OK", zap.String("confPath", confPath))
return
}
if err = m.Start(ctx); err != nil {
logger.Fatal("Failed to start services",
zap.String("confPath", confPath),
zap.Error(err),
)
}
<-ctx.Done()
m.Stop()
}