-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathxmux_test.go
More file actions
373 lines (324 loc) · 9.67 KB
/
Copy pathxmux_test.go
File metadata and controls
373 lines (324 loc) · 9.67 KB
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package xmux
import (
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"testing"
)
func home(w http.ResponseWriter, r *http.Request) {
fmt.Println("66666666")
name := Var(r)["aaa"]
// time.Sleep(time.Millisecond * 30)
m1 := map[string]string{
"message": name,
}
b, _ := json.Marshal(m1)
GetInstance(r).GetFuncName()
fmt.Println(GetInstance(r).GetUrl())
w.Write(b)
// GetInstance(r).Response.(*Response).Msg = time.Now().String()
}
func home2(w http.ResponseWriter, r *http.Request) {
// name := Var(r)["name"]
// time.Sleep(time.Millisecond * 30)
m2 := map[string]string{
"message": "asdfasdf",
}
GetInstance(r).Set("xmux_response", m2)
w.Write([]byte("aaaaa"))
}
func grouphome(w http.ResponseWriter, r *http.Request) {
fmt.Println("mmmmmmmm group")
w.Write([]byte("grouphome" + Var(r)["name"] + "-" + Var(r)["age"]))
}
func adminhandle(w http.ResponseWriter, r *http.Request) {
fmt.Println("mmmmmmmm admin")
}
func DictMe() *RouteGroup {
dict := NewRouteGroup().SetMeta(Meta{
Name: "我是菜单",
MenuType: "f",
})
dict.AddGroup(adminGroup())
return dict
}
func adminGroup() *RouteGroup {
admin := NewRouteGroup().Prefix("test").SetMeta(Meta{
Name: "后台",
MenuType: "c",
})
admin.Get("/admin/b", home).SetMeta(Meta{
Name: "admin",
MenuType: "b",
})
admin.Get("/admin", adminhandle).DelPageKeys("editor")
admin.Get("/aaa/adf{re:([a-z]{1,4})sf([0-9]{0,10})sd: name, age}", grouphome)
return admin
}
func userGroup() *RouteGroup {
user := NewRouteGroup().SetMeta(Meta{
Name: "用户管理菜单",
MenuType: "c",
})
// user.Get("/group", home).Use(CombineHandlers())
user.Get("/user/{asdfsdf}/{int:gg}", home).SetMeta(Meta{
Name: "用户查看",
MenuType: "b",
})
user.AddGroup(DictMe()).DelPostModule(postModule)
return user
}
func Post(w http.ResponseWriter, r *http.Request) (exit bool) {
fmt.Println("post")
return false
}
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
func PermissionTemplate(w http.ResponseWriter, r *http.Request) (post bool) {
// Get the permission of the corresponding URI, which is set by addpagekeys and delpagekeys
pages := GetInstance(r).GetPageKeys()
// If the length is 0, it means that anyone can access it
if len(pages) == 0 {
return false
}
// Get the corresponding role of the user and judge that it is all in
roles := []string{"editor"} //Obtain the user's permission from the database or redis
for _, role := range roles {
if _, ok := pages[role]; ok {
//What matches here is the existence of this permission. Continue to follow for so long
return false
}
}
// no permission
w.Write([]byte("no permission"))
return true
}
type MenuApi struct {
MenuId string `json:"menu_id" gorm:"primaryKey;size:50"` // 主键
Url string `json:"url" gorm:"size:255"`
Method string `json:"method" gorm:"size:255"`
Name string `json:"name" gorm:"size:255"`
MenuType string `json:"menu_type" gorm:"size:2"`
}
func TestMain(t *testing.T) {
// pool := NewPool()
router := NewRouter().AddModule(PermissionTemplate)
// router.HandleAll = LimitFixedWindowCounterTemplate
// router.HandleRecover = func(w http.ResponseWriter, r *http.Request) {
// w.Write([]byte("服务器错误"))
// }
// cth := gocache.NewCache[string, []byte](100, gocache.LFU)
// InitResponseCache(cth)
// router.AddModule(setkey, DefaultCacheTemplateCacheWithoutResponse).AddModule(Post)
router.AddPageKeys("admin", "editor")
// router.SetHeader("Access-Control-Allow-Origin", "*").
// SetHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
// router.AddGroup(Pprof())
// router.Enter = enter
// router.ModuleContinue = true
// router.Prefix("/api")
// router.EnableConnect = true
router.Get("/test/{aaaa}", home).SetMeta(Meta{
Name: "测试接口",
MenuType: "b",
})
// router.Get("/bar", home2).AddPageKeys("admin")
// router.Get("/post", pp).Use(pool.Middleware(heavyHandler))
// pf := router.PageKeyFuncMap()
// fmt.Println(pf)
// router.SetAddr(":8080")
router.AddGroup(userGroup())
// b, _ := json.MarshalIndent(router.menuTree, "", " ")
// fmt.Println(len(router.Routes()))
// Insert(router.Menus())
// 这里拿到的就是有权限的节点, 可以直接遍历 , url 和 method 存在, 那就是有权限,
// router.Menus() 是在本地缓存里面的, 唯一保存的 角色权限, 可以大大简化 go-admin 的权限校验,
// 直接在本地就能拿到用户有权限的 url 和 method, 不需要每次请求都去数据库查权限了, 直接在内存里校验就行了
// BuildMenuTree(router.Menus()) 这里是菜单树, 可以直接返回给前端
// 需要注意的是, setMeta 里面的 目录 和 菜单 节点的 MenuType 和 Name 不要有重复的, 不然权限校验会有问题, 因为权限是根据 menuId 来的, menuId 是根据 url method menuType name 生成的, 如果 menuType 和 name 重复了, 那就会有重复的 menuId, 权限校验就会有问题了
// BuildMenuTree(router.Menus()) 如果需要对菜单进行更细致的配置
// b, _ := json.MarshalIndent(router.Menus(), "", " ")
// a, _ := json.MarshalIndent(BuildRouteTree(router.Menus()), "", " ")
a, _ := json.MarshalIndent(FilterMenuTree(BuildRouteTree(router.Menus()), map[string]bool{"0b81fb97a1b254927c3491550098c20b": true}, ""), "", " ")
b, _ := json.MarshalIndent(FlattenMenuTree(FilterMenuTree(BuildRouteTree(router.Menus()), map[string]bool{"0b81fb97a1b254927c3491550098c20b": true}, "")), "", " ")
// // b, _ := json.MarshalIndent(BuildMenuTree(router.Menus()), "", " ")
fmt.Println(string(a))
fmt.Println(string(b))
log.Fatal(router.SetAddr(":19999").Run())
}
type Binding struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
func Recovery(key string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("panic: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
key := r.URL.Path
e := getEntry(key)
mu.Lock()
//---------- 生产者路径 ----------
if !e.done {
e.count++ // 正在计算
mu.Unlock() // 放锁去 IO
// 模拟耗时计算
// resp := []byte("这是 " + key + " 的处理结果")
next.ServeHTTP(w, r)
mu.Lock()
e.response = GetInstance(r).Get(key).([]byte)
e.done = true
e.cond.Broadcast()
mu.Unlock()
return
}
//---------- 消费者路径 ----------
e.count++
for !e.done {
e.cond.Wait() // 内部会临时放锁
}
data := append([]byte(nil), e.response...) // 锁内深拷贝
e.count--
if e.count == 0 { // 最后一个离开
delete(entries, key) // 安全删除
}
mu.Unlock()
w.Write(data)
})
}
}
// Middleware 返回 http.Handler 中间件
// opts: 可传入 KeyFunc,默认用 r.URL.Path
func (p *Pool) Middleware(next http.HandlerFunc, opts ...KeyFunc) http.HandlerFunc {
keyFn := func(r *http.Request) string { return r.URL.Path }
if len(opts) > 0 && opts[0] != nil {
keyFn = opts[0]
}
return func(w http.ResponseWriter, r *http.Request) {
key := keyFn(r)
e := p.getEntry(key)
p.mu.Lock()
// 生产者路径
if !e.done {
e.count++
p.mu.Unlock()
// 执行业务 handler 拿结果
rec := &responseRecorder{ResponseWriter: w, status: 200}
next(rec, r)
p.mu.Lock()
e.response = rec.body
e.done = true
e.cond.Broadcast()
p.mu.Unlock()
return
}
// 消费者路径
e.count++
for !e.done {
e.cond.Wait()
}
data := append([]byte(nil), e.response...)
e.count--
if e.count == 0 {
delete(p.data, key)
}
p.mu.Unlock()
// 把缓存内容写回客户端
w.Write(data)
}
}
// 内部拿 entry(锁内)
func (p *Pool) getEntry(key string) *entry {
p.mu.Lock()
defer p.mu.Unlock()
e := p.data[key]
if e == nil {
e = &entry{cond: sync.NewCond(&p.mu)}
p.data[key] = e
}
return e
}
// KeyFunc 允许调用方自定义分组 key
type KeyFunc func(r *http.Request) string
// responseRecorder 把响应内容截下来复用
type responseRecorder struct {
http.ResponseWriter
body []byte
status int
}
func (r *responseRecorder) Write(p []byte) (int, error) {
r.body = append(r.body, p...)
return len(p), nil
}
func postModule(w http.ResponseWriter, r *http.Request) bool {
fmt.Println("这是一个后置模块")
return false
}
// Pool 按 key 缓存请求结果
type Pool struct {
mu sync.Mutex
data map[string]*entry
}
type entry struct {
done bool
response []byte
count int32
cond *sync.Cond
}
func NewPool() *Pool {
return &Pool{data: make(map[string]*entry)}
}
var (
mu sync.Mutex // 只用一把 Lock,简化生命周期
entries = make(map[string]*entry)
)
// 拿到或新建 entry(锁内)
func getEntry(key string) *entry {
mu.Lock()
defer mu.Unlock()
e := entries[key]
if e == nil {
e = &entry{cond: sync.NewCond(&mu)}
entries[key] = e
}
return e
}
func pp(w http.ResponseWriter, r *http.Request) {
// a := make([]string, 0)
key := r.URL.Path
e := getEntry(key)
mu.Lock()
//---------- 生产者路径 ----------
if !e.done {
e.count++ // 正在计算
mu.Unlock() // 放锁去 IO
// 模拟耗时计算
resp := []byte("这是 " + key + " 的处理结果")
mu.Lock()
e.response = resp
e.done = true
e.cond.Broadcast()
mu.Unlock()
return
}
//---------- 消费者路径 ----------
e.count++
for !e.done {
e.cond.Wait() // 内部会临时放锁
}
data := append([]byte(nil), e.response...) // 锁内深拷贝
e.count--
if e.count == 0 { // 最后一个离开
delete(entries, key) // 安全删除
}
mu.Unlock()
w.Write(data)
}