forked from satyrius/gonx
-
Notifications
You must be signed in to change notification settings - Fork 1
/
filter.go
59 lines (53 loc) · 1.24 KB
/
filter.go
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package gonx
import "time"
// Filter interface for Entries channel limiting.
//
// Filter method should accept *Entry and return *Entry if it meets
// filter condition, otherwise it returns nil.
type Filter interface {
Reducer
Filter(*Entry) *Entry
}
// Datetime implements the Filter interface to filter Entries with timestamp fields within
// the specified datetime interval.
type Datetime struct {
Field string
Format string
Start time.Time
End time.Time
}
// Filter checks a field value to be in desired datetime range.
func (i *Datetime) Filter(entry *Entry) (validEntry *Entry) {
val, err := entry.Field(i.Field)
if err != nil {
// TODO handle error
return
}
t, err := time.Parse(i.Format, val)
if err != nil {
// TODO handle error
return
}
if i.withinBounds(t) {
validEntry = entry
}
return
}
// Reduce implements the Reducer interface. Go through input and apply Filter.
func (i *Datetime) Reduce(input chan *Entry, output chan *Entry) {
for entry := range input {
if valid := i.Filter(entry); valid != nil {
output <- valid
}
}
close(output)
}
func (i *Datetime) withinBounds(t time.Time) bool {
if t.Equal(i.Start) {
return true
}
if t.After(i.Start) && t.Before(i.End) {
return true
}
return false
}