-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
180 lines (155 loc) · 4.53 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package main
import (
"embed"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"sse-broker/funcs"
"sse-broker/sse"
"syscall"
"time"
"github.com/gin-gonic/gin"
)
var (
config *Config
accessLogFile *os.File
errorLogFile *os.File
appLogFile *os.File
)
//go:embed static/**
var staticFiles embed.FS
const version = "1.0.5"
// 监测服务关闭信号
func handleShutdown() {
// 创建一个 channel 来接收操作系统信号
signalChan := make(chan os.Signal, 1)
// 捕获 SIGINT (Ctrl+C) 和 SIGTERM (systemctl stop) 信号
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
// 等待信号
sig := <-signalChan
log.Printf("Received signal: %s. Shutting down...", sig)
sse.Stop()
sse.Dispose()
// 关闭日志文件
if accessLogFile != nil {
accessLogFile.Close()
}
if errorLogFile != nil {
errorLogFile.Close()
}
if appLogFile != nil {
appLogFile.Close()
}
os.Exit(0)
}
func init() {
// 设置Windows控制台为UTF-8编码
// if os.Getenv("OS") == "Windows_NT" {
// handle := windows.Handle(os.Stdout.Fd())
// var mode uint32
// windows.GetConsoleMode(handle, &mode)
// mode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
// windows.SetConsoleMode(handle, mode)
// }
var shortConfig string
var configPath string
shortVersion := flag.Bool("v", false, "show version")
versionFlag := flag.Bool("version", false, "show version")
flag.StringVar(&shortConfig, "c", "", "config file path")
flag.StringVar(&configPath, "config", "", "config file path")
flag.Parse()
if *versionFlag || *shortVersion {
fmt.Printf("Version: %s\n", version)
os.Exit(0)
}
if configPath == "" {
configPath = shortConfig
}
if configPath == "" {
if os.Getenv("OS") == "Windows_NT" {
configPath = "config.toml"
} else {
configPath = "/etc/sse-broker/config.toml"
}
}
baseDir := funcs.GetExecutionPath()
cfg, err := loadConfig(baseDir, configPath)
if err != nil {
fmt.Printf("Failed to load config: %v\n", err)
panic(fmt.Sprintf("Failed to load config: %v\n", err))
}
config = cfg
a, e, p := initLogger(baseDir, config)
accessLogFile = a
errorLogFile = e
appLogFile = p
sse.Start(sse.Config{
Server: struct {
Version string
Port int
}{Version: version, Port: config.Server.Port},
JWT: struct {
Secret string
Expire int
}{Secret: config.JWT.Secret, Expire: config.JWT.Expire},
Redis: struct {
Addrs []string
Password string
DB int
PoolSize int
}{Addrs: config.Redis.Addrs, Password: config.Redis.Password, DB: config.Redis.DB, PoolSize: config.Redis.PoolSize},
SSE: struct {
HeartbeatDuration time.Duration
DeviceUserExistDuration time.Duration
DeviceFrameExpireDuration time.Duration
DeviceFrameCacheSize int
}{
HeartbeatDuration: time.Duration(config.SSE.HeartbeatInterval) * time.Second,
DeviceUserExistDuration: time.Duration(config.SSE.HeartbeatInterval+5) * time.Second,
DeviceFrameExpireDuration: time.Duration(config.SSE.DeviceFrameExpire) * time.Second,
DeviceFrameCacheSize: config.SSE.DeviceFrameCacheSize,
},
})
}
func main() {
// 设置 Gin 运行模式为 release
gin.SetMode(gin.ReleaseMode)
go handleShutdown()
// 创建Gin引擎
engine := gin.Default()
// 设置静态文件路由
engine.GET("/static/*filepath", func(ctx *gin.Context) {
staticServer := http.FileServer(http.FS(staticFiles))
staticServer.ServeHTTP(ctx.Writer, ctx.Request)
})
engine.GET("/", func(ctx *gin.Context) {
ctx.Redirect(http.StatusMovedPermanently, "/static/index.html")
})
engine.GET("/favicon.ico", func(ctx *gin.Context) {
favicon, err := staticFiles.ReadFile("static/favicon.ico")
if err != nil {
ctx.String(http.StatusNotFound, "Favicon not found")
return
}
ctx.Data(http.StatusOK, "image/x-icon", favicon)
})
// 设置API路由
engine.GET("/events", sse.TokenCheck(), sse.HandleEvents)
engine.Any("/token", sse.HandleToken)
engine.Any("/send", sse.HandleSend)
engine.Any("/info", sse.HandleInfo)
engine.Any("/kick", sse.HandleKick)
instanceIP := sse.GetIP()
instancePort := config.Server.Port
log.Println("-----------------------------------------------")
log.Printf("SSE-Broker Started, Listening Port: %d\n", instancePort)
log.Printf("Instance IP: %s, Instance Version: %s\n", instanceIP, version)
log.Printf("API Page: http://%s:%d/\n", instanceIP, instancePort)
log.Printf("Demo Page: http://%s:%d/static/demo.html\n", instanceIP, instancePort)
log.Println("-----------------------------------------------")
// 启动服务
engine.Run(fmt.Sprintf(":%d", instancePort))
}