-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.go
100 lines (85 loc) · 2.32 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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"time"
"github.com/gin-gonic/gin"
)
var (
signalChan chan os.Signal
httpServer *http.Server
)
func newRouter() *gin.Engine {
if conf.Server.Debug {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
gin.DisableConsoleColor()
}
engine := gin.Default()
engine.POST(webhook, xrayWebhookHandler)
engine.Use(func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE")
c.Header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept")
c.Header("Access-Control-Max-Age", "1800")
if strings.ToUpper(c.Request.Method) == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
})
// TODO: AddRouter
apiGroup := engine.Group("/api")
{
apiGroup.POST("/project", createProjectHandler)
// apiGroup.PUT("/project/:id", updateProjectHandler)
apiGroup.GET("/start/:id", startProjectHandler)
apiGroup.GET("/stop/:id", stopProjectHandler)
apiGroup.GET("/projects", getProjectsHandler)
apiGroup.GET("/project/:id", getProjectHandler)
apiGroup.GET("/vuls", getVulsHandler)
}
engine.StaticFS("/static", FS(false))
engine.GET("/", func(c *gin.Context) {
c.Redirect(302, "/static")
})
return engine
}
func main() {
if _, err := getDefaultXrayConfig(); err != nil {
logger.Errorln(err)
return
}
router := newRouter()
httpServer := &http.Server{
Addr: fmt.Sprintf(":%d", conf.Server.Port),
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
go func() {
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Errorf("HTTP server listen: %s\n", err)
}
}()
logger.Debugf("HTTP Server Listening: http://127.0.0.1:%d", conf.Server.Port)
// 等待中断信号以优雅地关闭服务器
signalChan = make(chan os.Signal)
signal.Notify(signalChan, os.Interrupt)
sig := <-signalChan
logger.Println("Get Signal:", sig)
logger.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := httpServer.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
logger.Println("Server exiting")
}