-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathrouter.go
83 lines (68 loc) · 2.15 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package router
import (
"chat-room/api/v1"
"chat-room/pkg/common/response"
"chat-room/pkg/global/log"
"net/http"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func NewRouter() *gin.Engine {
gin.SetMode(gin.ReleaseMode)
server := gin.Default()
server.Use(Cors())
server.Use(Recovery)
// server.Use(gin.Recovery())
socket := RunSocekt
group := server.Group("")
{
group.GET("/user", v1.GetUserList)
group.GET("/user/:uuid", v1.GetUserDetails)
group.GET("/user/name", v1.GetUserOrGroupByName)
group.POST("/user/register", v1.Register)
group.POST("/user/login", v1.Login)
group.PUT("/user", v1.ModifyUserInfo)
group.POST("/friend", v1.AddFriend)
group.GET("/message", v1.GetMessage)
group.GET("/file/:fileName", v1.GetFile)
group.POST("/file", v1.SaveFile)
group.GET("/group/:uuid", v1.GetGroup)
group.POST("/group/:uuid", v1.SaveGroup)
group.POST("/group/join/:userUuid/:groupUuid", v1.JoinGroup)
group.GET("/group/user/:uuid", v1.GetGroupUsers)
group.GET("/socket.io", socket)
}
return server
}
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin") //请求头部
if origin != "" {
c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
}
//允许类型校验
if method == "OPTIONS" {
c.JSON(http.StatusOK, "ok!")
}
defer func() {
if err := recover(); err != nil {
log.Logger.Error("HttpError", zap.Any("HttpError", err))
}
}()
c.Next()
}
}
func Recovery(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
log.Logger.Error("gin catch error: ", log.Any("gin catch error: ", r))
c.JSON(http.StatusOK, response.FailMsg("系统内部错误"))
}
}()
c.Next()
}