forked from deanxv/coze-discord-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (65 loc) · 1.69 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
// @title COZE-DISCORD-PROXY
// @version 1.0.0
// @description COZE-DISCORD-PROXY 代理服务
// @BasePath
package main
import (
"context"
"coze-discord-proxy/common"
"coze-discord-proxy/common/config"
"coze-discord-proxy/discord"
"coze-discord-proxy/middleware"
"coze-discord-proxy/router"
"errors"
"github.com/gin-gonic/gin"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go discord.StartBot(ctx, discord.BotToken)
common.SetupLogger()
common.SysLog("COZE-DISCORD-PROXY " + common.Version + " started")
if os.Getenv("GIN_MODE") != "debug" {
gin.SetMode(gin.ReleaseMode)
}
if config.DebugEnabled {
common.SysLog("running in debug mode")
}
// Initialize HTTP server
server := gin.New()
server.Use(gin.Recovery())
server.Use(middleware.RequestId())
middleware.SetUpLogger(server)
router.SetApiRouter(server)
var port = os.Getenv("PORT")
if port == "" {
port = strconv.Itoa(*common.Port)
}
srv := &http.Server{
Addr: ":" + port,
Handler: server,
}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
common.FatalLog("failed to start HTTP server: " + err.Error())
}
}()
// 等待中断信号
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
// 收到信号后取消 context
cancel()
// 给 HTTP 服务器一些时间来关闭
ctxShutDown, cancelShutDown := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelShutDown()
if err := srv.Shutdown(ctxShutDown); err != nil {
common.FatalLog("HTTP server Shutdown failed:" + err.Error())
}
}