Commit 564ef69718207b6ebf7eb0897706e3019564d051
1 parent
feb3471e7a
Exists in
master
added simple sql filter string parser/generator
Showing
1 changed file
with
76 additions
and
0 deletions
Show diff stats
filtering.go
... | ... | @@ -0,0 +1,76 @@ |
1 | +package webutility | |
2 | + | |
3 | +import ( | |
4 | + "fmt" | |
5 | + "net/http" | |
6 | + "strings" | |
7 | +) | |
8 | + | |
9 | +type Filter map[string]string | |
10 | + | |
11 | +func (fs Filter) validate(validFilters []string) (Filter, bool) { | |
12 | + goodFilters := make(map[string]string) | |
13 | + cnt := 0 | |
14 | + len := 0 | |
15 | + for f, _ := range fs { | |
16 | + len++ | |
17 | + for _, v := range validFilters { | |
18 | + if f == v { | |
19 | + cnt++ | |
20 | + goodFilters[f] = fs[f] | |
21 | + } | |
22 | + } | |
23 | + } | |
24 | + | |
25 | + result := true | |
26 | + if len > 0 && cnt == 0 { | |
27 | + // if no valid filters are found declare filtering request as invalid | |
28 | + result = false | |
29 | + } | |
30 | + | |
31 | + return goodFilters, result | |
32 | +} | |
33 | + | |
34 | +// requires input in format: "param1::value1|param2::value2..." | |
35 | +func ParseFilters(req *http.Request, header string) (filters Filter) { | |
36 | + q := req.FormValue(header) | |
37 | + q = strings.Trim(q, "\"") | |
38 | + kvp := strings.Split(q, "|") | |
39 | + filters = make(map[string]string, len(kvp)) | |
40 | + | |
41 | + for i, _ := range kvp { | |
42 | + kv := strings.Split(kvp[i], "::") | |
43 | + if len(kv) == 2 { | |
44 | + key := kv[0] | |
45 | + val := kv[1] | |
46 | + filters[key] = val | |
47 | + } | |
48 | + } | |
49 | + | |
50 | + return filters | |
51 | +} | |
52 | + | |
53 | +func MakeFilterString(prefix string, filters Filter, validFilters []string) (res string, ok bool) { | |
54 | + if prefix != "" { | |
55 | + prefix += "." | |
56 | + } | |
57 | + if len(filters) == 0 { | |
58 | + return "", true | |
59 | + } | |
60 | + | |
61 | + filters, ok = filters.validate(validFilters) | |
62 | + if !ok { | |
63 | + return "", ok | |
64 | + } | |
65 | + | |
66 | + for k, v := range filters { | |
67 | + if res != "" { | |
68 | + res += " and " | |
69 | + } else { | |
70 | + res += " where " | |
71 | + } | |
72 | + res += fmt.Sprintf("%s%s = '%s'", prefix, k, v) | |
73 | + } | |
74 | + | |
75 | + return res, ok | |
76 | +} | ... | ... |