-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter.go
123 lines (112 loc) · 2.16 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Copyright (c) 2020 Blockwatch Data Inc.
// Author: [email protected]
package blockwatch
import (
"fmt"
"net/url"
"strings"
)
type FilterMode int
const (
FilterModeEqual FilterMode = iota
FilterModeNotEqual
FilterModeGt
FilterModeGte
FilterModeLt
FilterModeLte
FilterModeIn
FilterModeNotIn
FilterModeRange
FilterModeRegexp
FilterModeInvalid
)
type Filter struct {
Field string
Mode FilterMode
Value string
}
func NewFilter(field string, mode FilterMode, value string) *Filter {
return &Filter{
Field: field,
Mode: mode,
Value: value,
}
}
func (f Filter) String() string {
return fmt.Sprintf("%s.%s=%s", f.Field, f.Mode, f.Value)
}
func (f Filter) AppendQuery(q url.Values) {
q.Add(fmt.Sprintf("%s.%s", f.Field, f.Mode), f.Value)
}
func ParseFilterMode(s string) FilterMode {
switch strings.ToLower(s) {
case "", "eq":
return FilterModeEqual
case "ne":
return FilterModeNotEqual
case "gt":
return FilterModeGt
case "gte":
return FilterModeGte
case "lt":
return FilterModeLt
case "lte":
return FilterModeLte
case "in":
return FilterModeIn
case "nin":
return FilterModeNotIn
case "rg":
return FilterModeRange
case "re":
return FilterModeRegexp
default:
return FilterModeInvalid
}
}
func (m FilterMode) String() string {
switch m {
case FilterModeEqual:
return "eq"
case FilterModeNotEqual:
return "ne"
case FilterModeGt:
return "gt"
case FilterModeGte:
return "gte"
case FilterModeLt:
return "lt"
case FilterModeLte:
return "lte"
case FilterModeIn:
return "in"
case FilterModeNotIn:
return "nin"
case FilterModeRange:
return "rg"
case FilterModeRegexp:
return "re"
default:
return "" // assuming equal
}
}
// col_name.{ne|gt|gte|lt|lte|in|nin|re|rg}=value
func ParseFilter(key string, val string) (*Filter, error) {
var fkey, mkey string
if fields := strings.Split(key, "."); len(fields) == 2 {
fkey, mkey = fields[0], fields[1]
} else {
fkey = fields[0]
mkey = FilterModeEqual.String()
}
mode := ParseFilterMode(mkey)
if mode == FilterModeInvalid {
return nil, fmt.Errorf("invalid filter mode '%s'", mkey)
}
f := &Filter{
Field: fkey,
Mode: mode,
Value: val,
}
return f, nil
}