-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsingle.go
61 lines (53 loc) · 1.19 KB
/
single.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
package nano
import (
"github.com/RomiChan/syncx"
)
// Option 配置项
type Option[K comparable] func(*Single[K])
// Single 反并发
type Single[K comparable] struct {
group syncx.Map[K, struct{}]
key func(ctx *Ctx) K
post func(ctx *Ctx)
}
// WithKeyFn 指定反并发的 Key
func WithKeyFn[K comparable](fn func(ctx *Ctx) K) Option[K] {
return func(s *Single[K]) {
s.key = fn
}
}
// WithPostFn 指定反并发拦截后的操作
func WithPostFn[K comparable](fn func(ctx *Ctx)) Option[K] {
return func(s *Single[K]) {
s.post = fn
}
}
// NewSingle 创建反并发中间件
func NewSingle[K comparable](op ...Option[K]) *Single[K] {
s := Single[K]{}
for _, option := range op {
option(&s)
}
return &s
}
// Apply 为指定 Engine 添加反并发功能
func (s *Single[K]) Apply(engine *Engine) {
engine.UseMidHandler(func(ctx *Ctx) bool {
if s.key == nil {
return true
}
key := s.key(ctx)
if _, ok := s.group.Load(key); ok {
if s.post != nil {
defer s.post(ctx)
}
return false
}
s.group.Store(key, struct{}{})
ctx.State["__single-key__"] = key
return true
})
engine.UsePostHandler(func(ctx *Ctx) {
s.group.Delete(ctx.State["__single-key__"].(K))
})
}