-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
108 lines (91 loc) · 2.47 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
package main
import (
"GoWAFer/api"
_ "GoWAFer/docs"
"GoWAFer/migrate"
"GoWAFer/pkg/config"
"GoWAFer/pkg/database"
"GoWAFer/pkg/utils/graceful"
"GoWAFer/web"
"context"
"errors"
"fmt"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"gopkg.in/natefinch/lumberjack.v2"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
// @title GoWAFer
// @description Golang编写的一款基于反向代理模式的web防火墙应用 By supercat0867
// @version v1.0
func main() {
graceful.Welcome()
// 读取配置文章
conf := config.ReadConfig()
fmt.Println("配置文件加载成功")
// 配置日志输出
log.SetOutput(&lumberjack.Logger{
Filename: "log/application.log",
MaxSize: 10,
MaxBackups: 3,
MaxAge: 28,
Compress: true,
})
// 创建数据库连接
db, err := database.InitDB()
if err != nil {
panic(fmt.Sprintf("数据库连接失败:%v", err))
}
fmt.Println("数据库连接成功")
rdb := database.InitRedis()
// 迁移数据库
migrate.AutoMigrateAndInsertData(db)
fmt.Println("数据库迁移成功")
r := gin.Default()
store := cookie.NewStore([]byte(conf.Secret.SessionSecretKey))
store.Options(sessions.Options{
MaxAge: 60 * 60 * 24 * 30,
Path: "/",
HttpOnly: true,
//Secure: true,
})
r.Use(sessions.Sessions("waf-session", store))
// 加载静态资源
r.Static("/static", "./static")
// 加载模版文件
r.LoadHTMLGlob("templates/**")
// swagger 文档
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
// 注册页面路由
web.RegisterWebHandler(r, db, conf)
// 注册API路由、注册反向代理路由
api.RegisterAllHandlers(r, db, rdb, conf)
// 创建一个监听系统终止信号的通道
stopChan := make(chan os.Signal, 1)
signal.Notify(stopChan, syscall.SIGINT, syscall.SIGTERM)
// 启动waf服务
srv := &http.Server{Addr: ":8080", Handler: r}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
fmt.Printf("listen: %s\n", err)
}
}()
// 阻塞,直到接收到系统终止信号
<-stopChan
fmt.Println("Shutting down server...")
// 执行清理操作
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
fmt.Printf("Server Shutdown: %v", err)
}
fmt.Println("Server gracefully stopped")
}