-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
121 lines (99 loc) · 2.37 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
114
115
116
117
118
119
120
121
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"runtime/debug"
"syscall"
"github.com/zwcway/castserver-go/common/config"
"github.com/zwcway/castserver-go/common/database"
"github.com/zwcway/castserver-go/common/log"
"github.com/zwcway/castserver-go/common/utils"
)
var (
options map[string]string
version bool
help bool
daemon bool
is6 bool
logFile string
configFile string
netInterface string
detectInterface string
)
func init() {
flag.StringVar(&configFile, "c", "", "specify configuration file")
flag.StringVar(&netInterface, "i", "", "listen interface")
flag.StringVar(&detectInterface, "detect-interface", "", "detect listen interface")
flag.StringVar(&logFile, "l", "", "log file")
flag.BoolVar(&version, "v", false, "show current version of clash")
flag.BoolVar(&daemon, "D", false, "running in background")
flag.BoolVar(&help, "h", false, "show this message")
flag.BoolVar(&is6, "6", false, "use IPV6 net")
flag.Parse()
options = make(map[string]string)
flag.Visit(func(f *flag.Flag) { options[f.Name] = f.Value.String() })
}
func exit(code int, usage bool, format string, val ...any) {
fmt.Printf(format, val...)
if usage {
os.Stdout.Sync()
flag.Usage()
}
os.Exit(code)
}
func main() {
exitCode := 0
if version {
exit(exitCode, false, "Version: %s", config.VERSION)
}
if help {
exit(exitCode, true, "")
}
log, logClose, err := log.NewLogger(logFile, daemon)
if err != nil {
exit(2, true, err.Error())
}
// 用于通知主程序退出
signalChannel := make(chan os.Signal, 2)
// 用于通知子协程退出
rootCtx, ctxCancel := utils.NewContext().WithSignal(signalChannel).WithLogger(log).WithCancel()
err = config.FromOptions(rootCtx, options)
if err != nil {
exit(2, false, err.Error())
}
debug.SetMaxThreads(config.RuntimeThreads)
database.Init(rootCtx, config.DB)
err = initModules(rootCtx)
if err != nil {
exitCode = 255
goto __exit__
}
err = startModules()
if err != nil {
exitCode = 254
goto __exit__
}
// 阻塞
signal.Notify(signalChannel,
syscall.SIGINT,
syscall.SIGKILL,
syscall.SIGTERM,
syscall.SIGQUIT,
syscall.SIGABRT,
)
<-signalChannel
ctxCancel()
close(signalChannel)
log.Info("exit")
__exit__:
if err != nil {
fmt.Println(err.Error())
}
deinitModules()
if logClose != nil {
logClose()
}
os.Exit(exitCode)
}