github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/router/middleware.go (about) 1 package router 2 3 import ( 4 "sync" 5 ) 6 7 type ( 8 // 中间件接口 9 IMiddleware interface { 10 Handler(ctx IContext) 11 } 12 13 // 中间件名称接口 14 IMiddlewareName interface { 15 Name() string 16 } 17 18 // 中间件重置接口 19 // 重置接口用于实现特定成员手动清空 20 // NOTE:改函数被调用有当Handler执行完毕并回收中 21 IMiddlewareRest interface { 22 Rest() 23 } 24 25 TMiddlewareManager struct { 26 middlewares map[string]func(IRouter) IMiddleware 27 names []string // 28 lock sync.RWMutex // 同步性不重要暂时不加锁 29 } 30 ) 31 32 func newMiddlewareManager() *TMiddlewareManager { 33 return &TMiddlewareManager{ 34 middlewares: make(map[string]func(IRouter) IMiddleware), 35 } 36 37 } 38 39 // 有序返回所有中间件名称 顺序依据注册顺序 40 func (self *TMiddlewareManager) Names() []string { 41 return self.names 42 } 43 44 func (self *TMiddlewareManager) Contain(key string) bool { 45 self.lock.RLock() 46 _, ok := self.middlewares[key] 47 self.lock.RUnlock() 48 return ok 49 } 50 51 func (self *TMiddlewareManager) Add(key string, value func(IRouter) IMiddleware) { 52 self.lock.Lock() 53 defer self.lock.Unlock() 54 55 if _, exsit := self.middlewares[key]; !exsit { 56 self.middlewares[key] = value 57 self.names = append(self.names, key) // # 保存添加顺序 58 } else { 59 log.Warn("middleware key:" + key + " already exists") 60 } 61 } 62 63 func (self *TMiddlewareManager) Set(key string, value func(IRouter) IMiddleware) { 64 self.lock.Lock() 65 defer self.lock.Unlock() 66 67 if _, ok := self.middlewares[key]; ok { 68 self.middlewares[key] = value 69 } else { 70 log.Warn("middleware key:" + key + " does not exists") 71 } 72 } 73 74 func (self *TMiddlewareManager) Get(key string) func(IRouter) IMiddleware { 75 self.lock.RLock() 76 defer self.lock.RUnlock() 77 return self.middlewares[key] 78 } 79 80 func (self *TMiddlewareManager) Del(key string) { 81 self.lock.Lock() 82 defer self.lock.Unlock() 83 84 delete(self.middlewares, key) 85 for i, n := range self.names { 86 if n == key { 87 self.names = append(self.names[:i], self.names[i+1:]...) 88 break 89 } 90 } 91 }