intercept.go 716 字节
Newer Older
Y
Your Name 已提交
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
package listener

import "sync"

//InterceptFunc 拦截函数
type InterceptFunc func(event interface{}) error

//Intercept 拦截器
type Intercept struct {
	callbacks []InterceptFunc
	locker    sync.RWMutex
}

//NewIntercept 创建拦截器
func NewIntercept() *Intercept {
	return &Intercept{
		callbacks: nil,
		locker:    sync.RWMutex{},
	}
}

//Add add
func (i *Intercept) Add(f func(v interface{}) error) {
	i.locker.Lock()
	i.callbacks = append(i.callbacks, InterceptFunc(f))
	i.locker.Unlock()
}

//Call call
func (i *Intercept) Call(v interface{}) error {
	i.locker.RLock()
	fs := i.callbacks
	i.locker.RUnlock()

	for _, f := range fs {
		err := f(v)
		if err != nil {

			return err
		}
	}
	return nil
}