Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
ln/filter.go
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
67 lines (54 sloc)
1.48 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ln | |
import ( | |
"context" | |
"io" | |
"sync" | |
) | |
// Filter interface for defining chain filters | |
type Filter interface { | |
Apply(ctx context.Context, e Event) bool | |
Run() | |
Close() | |
} | |
// FilterFunc allows simple functions to implement the Filter interface | |
type FilterFunc func(ctx context.Context, e Event) bool | |
// Apply implements the Filter interface | |
func (ff FilterFunc) Apply(ctx context.Context, e Event) bool { | |
return ff(ctx, e) | |
} | |
// 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 | |
func (w *WriterFilter) Apply(ctx context.Context, e Event) bool { | |
output, err := w.Formatter.Format(ctx, e) | |
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 | |
var NilFilter = FilterFunc(func(_ context.Context, e Event) bool { return true }) |