总体概括
filter.go按照官方文件的顺序看,那样有点好不好理解,按照这个概括看稍微容易点
func NewRecorder(w Interface) *Recorder
创建一个新的记录器 创建的时候先实例化一个空的记录器,然后使用Filter对w进行过滤
func Filter(w Interface, f FilterFunc) Interface
具体实现都是有filterWatch实现的,所以先实例化一个filterWatch,将w,和f传给所以先实例化一个filterWatch
然后在使用和f传给所以先实例化一个filterWatch的loop方法进行过滤
func (r *Recorder) record(in Event) (Event, bool)
将event追加到r的evnts中并返回
func (r *Recorder) Events() []Event
//复制Events
func (fw *filteredWatch) ResultChan() <-chan Event
func (fw *filteredWatch) Stop()
func (fw *filteredWatch) loop()过滤器的具体实现
出现的数据结构
//从字面上理解是过滤的watch,过滤什么呢?先看具体包含了哪些内容,incomming Interface类型,一个result管道,一个过滤函数
//带着疑惑往后面看,看看到底过滤了什么玩意,此处为疑问1
type filteredWatch struct {
incoming Interface
result chan Event
f FilterFunc
}
//记录器,一个interface,一个锁,一个事件组。
type Recorder struct {
Interface
lock sync.Mutex
events []Event
}
一个func类型的数据FilterFunc 具体实现是在哪呢 此处为疑问2
type FilterFunc func(in Event) (out Event, keep bool)
filteredWatch的方法
//从filteredWatch中读取事件
func (fw *filteredWatch) ResultChan() <-chan Event {
return fw.result
}
// Stop stops the upstream watch, which will eventually stop this watch.
//filteredWatch停止接收数据
func (fw *filteredWatch) Stop() {
fw.incoming.Stop()
}
// loop waits for new values, filters them, and resends them.
//incomming是interface类型,interface类型有个获取result的管道。
//读取 incomming的数据,然后执行了 fw.f(event),f是FilterFunc类型,同疑问2
//从提看这个方法就是将filteredWatch的incomming数据处理后传给result,大概就明白了疑问1
func (fw *filteredWatch) loop() {
defer close(fw.result)
for {
event, ok := <-fw.incoming.ResultChan()
if !ok {
break
}
filtered, keep := fw.f(event)
if keep {
fw.result <- filtered
}
}
}
//NewRecorder生成一个新的记录器,传入和Interface类型的数据,首先实例化一个空的记录器,
//然后使用Filter函数给Interface赋值
//Filter函数,函数有两个参数一个是Interface类型,一个是FilterFunc类型,这个类型再次出现了,看看实际参数是r.record
//此处就明白了疑问2
func NewRecorder(w Interface) *Recorder {
r := &Recorder{}
r.Interface = Filter(w, r.record)
return r
}
//Filter函数中实例了一个filteredWatch,并使用了loop方法
func Filter(w Interface, f FilterFunc) Interface {
fw := &filteredWatch{
incoming: w,
result: make(chan Event),
f: f,
}
go fw.loop()
return fw
}
func (r *Recorder) record(in Event) (Event, bool) {
r.lock.Lock()
defer r.lock.Unlock()
r.events = append(r.events, in)
return in, true
}
// Events returns a copy of the events sent across this recorder.
func (r *Recorder) Events() []Event {
r.lock.Lock()
defer r.lock.Unlock()
copied := make([]Event, len(r.events))
copy(copied, r.events)
return copied
}