2017-03-29 07:26:50 +00:00
|
|
|
package ln
|
|
|
|
|
|
|
|
import (
|
2017-12-13 18:43:58 +00:00
|
|
|
"context"
|
2017-03-29 07:26:50 +00:00
|
|
|
"io"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Filter interface for defining chain filters
|
|
|
|
type Filter interface {
|
2017-12-13 18:43:58 +00:00
|
|
|
Apply(ctx context.Context, e Event) bool
|
2017-03-29 07:26:50 +00:00
|
|
|
Run()
|
|
|
|
Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
// FilterFunc allows simple functions to implement the Filter interface
|
2017-12-13 18:43:58 +00:00
|
|
|
type FilterFunc func(ctx context.Context, e Event) bool
|
2017-03-29 07:26:50 +00:00
|
|
|
|
|
|
|
// Apply implements the Filter interface
|
2017-12-13 18:43:58 +00:00
|
|
|
func (ff FilterFunc) Apply(ctx context.Context, e Event) bool {
|
|
|
|
return ff(ctx, e)
|
2017-03-29 07:26:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Run implements the Filter interface
|
|
|
|
func (ff FilterFunc) Run() {}
|
|
|
|
|
|
|
|
// Close implements the Filter interface
|
|
|
|
func (ff FilterFunc) Close() {}
|
|
|
|
|
|
|
|
// WriterFilter implements a filter, which arbitrarily writes to an io.Writer
|
|
|
|
type WriterFilter struct {
|
|
|
|
sync.Mutex
|
|
|
|
Out io.Writer
|
|
|
|
Formatter Formatter
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewWriterFilter creates a filter to add to the chain
|
|
|
|
func NewWriterFilter(out io.Writer, format Formatter) *WriterFilter {
|
|
|
|
if format == nil {
|
|
|
|
format = DefaultFormatter
|
|
|
|
}
|
|
|
|
return &WriterFilter{
|
|
|
|
Out: out,
|
|
|
|
Formatter: format,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Apply implements the Filter interface
|
2017-12-13 18:43:58 +00:00
|
|
|
func (w *WriterFilter) Apply(ctx context.Context, e Event) bool {
|
|
|
|
output, err := w.Formatter.Format(ctx, e)
|
2017-03-29 07:26:50 +00:00
|
|
|
if err == nil {
|
|
|
|
w.Lock()
|
|
|
|
w.Out.Write(output)
|
|
|
|
w.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run implements the Filter interface
|
|
|
|
func (w *WriterFilter) Run() {}
|
|
|
|
|
|
|
|
// Close implements the Filter interface
|
|
|
|
func (w *WriterFilter) Close() {}
|
|
|
|
|
|
|
|
// NilFilter is safe to return as a Filter, but does nothing
|
2017-12-13 18:43:58 +00:00
|
|
|
var NilFilter = FilterFunc(func(_ context.Context, e Event) bool { return true })
|