/
router.go
69 lines (57 loc) · 1.71 KB
/
router.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
package bootstrap
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/shonsama/RATVS-ROS-Topic-Unified-Visualization-System/api-server/app/middleware"
"github.com/shonsama/RATVS-ROS-Topic-Unified-Visualization-System/api-server/global"
"github.com/shonsama/RATVS-ROS-Topic-Unified-Visualization-System/api-server/routes"
)
func setupRouter() *gin.Engine {
if global.App.Config.App.Env == "production" {
gin.SetMode(gin.ReleaseMode)
}
router := gin.New()
router.Use(gin.Logger(), middleware.CustomRecovery())
// 跨域处理
router.Use(middleware.Cors())
// 前端项目静态资源
// router.StaticFile("/", "./static/dist/index.html")
// router.Static("/assets", "./static/dist/assets")
// router.StaticFile("/favicon.ico", "./static/dist/favicon.ico")
// 其他静态资源
// router.Static("/public", "./static")
// router.Static("/storage", "./storage/app/public")
// 注册 api 分组路由
apiGroup := router.Group("")
routes.SetApiGroupRoutes(apiGroup)
return router
}
func RunServer() {
r := setupRouter()
srv := &http.Server{
Addr: ":" + global.App.Config.App.Port,
Handler: r,
}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
}