-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
executable file
·344 lines (292 loc) · 8.2 KB
/
http.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package xohttp
import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"github.com/gin-gonic/gin"
"github.com/opentracing/opentracing-go"
"github.com/xochat/xochat_im_server_lib/pkg/cache"
"github.com/xochat/xochat_im_server_lib/pkg/log"
"go.uber.org/zap"
)
// UserRole 用户角色
type UserRole string
const (
// Admin 管理员
Admin UserRole = "admin"
// SuperAdmin 超级管理员
SuperAdmin UserRole = "superAdmin"
)
// XOHttp XOHttp
type XOHttp struct {
r *gin.Engine
pool sync.Pool
}
// New New
func New() *XOHttp {
l := &XOHttp{
r: gin.New(),
pool: sync.Pool{},
}
l.r.Use(gin.Recovery())
l.pool.New = func() interface{} {
return allocateContext()
}
return l
}
func allocateContext() *Context {
return &Context{Context: nil, lg: log.NewTLog("context")}
}
// Context Context
type Context struct {
*gin.Context
lg log.Log
}
func (c *Context) reset() {
c.Context = nil
}
// ResponseError ResponseError
func (c *Context) ResponseError(err error) {
c.JSON(http.StatusBadRequest, gin.H{
"msg": err.Error(),
"status": http.StatusBadRequest,
})
}
// ResponseErrorf ResponseErrorf
func (c *Context) ResponseErrorf(msg string, err error) {
if err != nil {
c.lg.Error(msg, zap.Error(err), zap.String("path", c.FullPath()))
}
c.JSON(http.StatusBadRequest, gin.H{
"msg": msg,
"status": http.StatusBadRequest,
})
}
// ResponseErrorWithStatus ResponseErrorWithStatus
func (c *Context) ResponseErrorWithStatus(err error, status int) {
c.JSON(http.StatusBadRequest, gin.H{
"msg": err.Error(),
"status": status,
})
}
// GetPage 获取页参数
func (c *Context) GetPage() (pageIndex int64, pageSize int64) {
pageIndex, _ = strconv.ParseInt(c.Query("page_index"), 10, 64)
pageSize, _ = strconv.ParseInt(c.Query("page_size"), 10, 64)
if pageIndex <= 0 {
pageIndex = 1
}
if pageSize <= 0 {
pageSize = 15
}
return
}
// ResponseOK 返回成功
func (c *Context) ResponseOK() {
c.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
})
}
// Response Response
func (c *Context) Response(data interface{}) {
c.JSON(http.StatusOK, data)
}
// ResponseWithStatus ResponseWithStatus
func (c *Context) ResponseWithStatus(status int, data interface{}) {
c.JSON(status, data)
}
// GetLoginUID 获取当前登录的用户uid
func (c *Context) GetLoginUID() string {
return c.MustGet("uid").(string)
}
// GetAppID appID
func (c *Context) GetAppID() string {
return c.GetHeader("appid")
}
// GetLoginName 获取当前登录的用户名字
func (c *Context) GetLoginName() string {
return c.MustGet("name").(string)
}
// GetLoginRole 获取当前登录用户的角色
func (c *Context) GetLoginRole() string {
return c.GetString("role")
}
// GetSpanContext 获取当前请求的span context
func (c *Context) GetSpanContext() opentracing.SpanContext {
return c.MustGet("spanContext").(opentracing.SpanContext)
}
// CheckLoginRole 检查登录角色权限
func (c *Context) CheckLoginRole() error {
role := c.GetLoginRole()
if role == "" {
return errors.New("登录用户角色错误")
}
if role != string(Admin) && role != string(SuperAdmin) {
return errors.New("该用户无权执行此操作")
}
return nil
}
// CheckLoginRoleIsSuperAdmin 检查登录用户为超级管理员
func (c *Context) CheckLoginRoleIsSuperAdmin() error {
role := c.GetLoginRole()
if role == "" {
return errors.New("登录用户角色错误")
}
if role != string(SuperAdmin) {
return errors.New("该用户无权执行此操作")
}
return nil
}
// HandlerFunc HandlerFunc
type HandlerFunc func(c *Context)
// XOHttpHandler XOHttpHandler
func (l *XOHttp) XOHttpHandler(handlerFunc HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
hc := l.pool.Get().(*Context)
hc.reset()
hc.Context = c
defer l.pool.Put(hc)
handlerFunc(hc)
//handlerFunc(&Context{Context: c})
}
}
// Run Run
func (l *XOHttp) Run(addr ...string) error {
return l.r.Run(addr...)
}
func (l *XOHttp) RunTLS(addr, certFile, keyFile string) error {
return l.r.RunTLS(addr, certFile, keyFile)
}
// POST POST
func (l *XOHttp) POST(relativePath string, handlers ...HandlerFunc) {
l.r.POST(relativePath, l.handlersToGinHandleFuncs(handlers)...)
}
// GET GET
func (l *XOHttp) GET(relativePath string, handlers ...HandlerFunc) {
l.r.GET(relativePath, l.handlersToGinHandleFuncs(handlers)...)
}
// Any Any
func (l *XOHttp) Any(relativePath string, handlers ...HandlerFunc) {
l.r.Any(relativePath, l.handlersToGinHandleFuncs(handlers)...)
}
// Static Static
func (l *XOHttp) Static(relativePath string, root string) {
l.r.Static(relativePath, root)
}
// LoadHTMLGlob LoadHTMLGlob
func (l *XOHttp) LoadHTMLGlob(pattern string) {
l.r.LoadHTMLGlob(pattern)
}
// UseGin UseGin
func (l *XOHttp) UseGin(handlers ...gin.HandlerFunc) {
l.r.Use(handlers...)
}
// Use Use
func (l *XOHttp) Use(handlers ...HandlerFunc) {
l.r.Use(l.handlersToGinHandleFuncs(handlers)...)
}
// ServeHTTP ServeHTTP
func (l *XOHttp) ServeHTTP(w http.ResponseWriter, req *http.Request) {
l.r.ServeHTTP(w, req)
}
// Group Group
func (l *XOHttp) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
return newRouterGroup(l.r.Group(relativePath, l.handlersToGinHandleFuncs(handlers)...), l)
}
// HandleContext HandleContext
func (l *XOHttp) HandleContext(c *Context) {
l.r.HandleContext(c.Context)
}
func (l *XOHttp) handlersToGinHandleFuncs(handlers []HandlerFunc) []gin.HandlerFunc {
newHandlers := make([]gin.HandlerFunc, 0, len(handlers))
if handlers != nil {
for _, handler := range handlers {
newHandlers = append(newHandlers, l.XOHttpHandler(handler))
}
}
return newHandlers
}
// AuthMiddleware 认证中间件
func (l *XOHttp) AuthMiddleware(cache cache.Cache, tokenPrefix string, log log.Log) HandlerFunc {
return func(c *Context) {
token := c.GetHeader("token")
if token == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"msg": "token不能为空,请先登录!",
})
log.Error("token 为空")
return
}
uidAndName := GetLoginUID(token, tokenPrefix, cache)
if strings.TrimSpace(uidAndName) == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"msg": "请先登录!",
})
log.Error(fmt.Sprintf("账号 %s 未登录; token=%s", uidAndName, token))
return
}
uidAndNames := strings.Split(uidAndName, "@")
if len(uidAndNames) < 2 {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"msg": "token有误!",
})
log.Error(fmt.Sprintf("token 错误 %s; token=%s", uidAndName, token))
return
}
c.Set("uid", uidAndNames[0])
c.Set("name", uidAndNames[1])
if len(uidAndNames) > 2 {
c.Set("role", uidAndNames[2])
}
c.Next()
}
}
// GetLoginUID GetLoginUID
func GetLoginUID(token string, tokenPrefix string, cache cache.Cache) string {
uid, err := cache.Get(tokenPrefix + token)
if err != nil {
return ""
}
return uid
}
// RouterGroup RouterGroup
type RouterGroup struct {
*gin.RouterGroup
L *XOHttp
}
func newRouterGroup(g *gin.RouterGroup, l *XOHttp) *RouterGroup {
return &RouterGroup{RouterGroup: g, L: l}
}
// POST POST
func (r *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) {
r.RouterGroup.POST(relativePath, r.L.handlersToGinHandleFuncs(handlers)...)
}
// GET GET
func (r *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) {
r.RouterGroup.GET(relativePath, r.L.handlersToGinHandleFuncs(handlers)...)
}
// DELETE DELETE
func (r *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) {
r.RouterGroup.DELETE(relativePath, r.L.handlersToGinHandleFuncs(handlers)...)
}
// PUT PUT
func (r *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) {
r.RouterGroup.PUT(relativePath, r.L.handlersToGinHandleFuncs(handlers)...)
}
// CORSMiddleware 跨域
func CORSMiddleware() HandlerFunc {
return func(c *Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, token, accept, origin, Cache-Control, X-Requested-With, appid, noncestr, sign, timestamp")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT,DELETE,PATCH")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}