Blame view

filtering.go 1.68 KB
564ef6971   Marko Tikvić   added simple sql ...
1
2
3
4
5
  package webutility
  
  import (
  	"fmt"
  	"net/http"
d869bd3f2   Marko Tikvić   filtering fix
6
  	"net/url"
564ef6971   Marko Tikvić   added simple sql ...
7
8
9
10
  	"strings"
  )
  
  type Filter map[string]string
ab548c502   Marko Tikvić   added Valid() to ...
11
12
13
14
15
16
17
  func (f *Filter) Size() int {
  	return len(*f)
  }
  
  func (f *Filter) Valid() bool {
  	return len(*f) > 0
  }
564ef6971   Marko Tikvić   added simple sql ...
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
  func (fs Filter) validate(validFilters []string) (Filter, bool) {
  	goodFilters := make(map[string]string)
  	cnt := 0
  	len := 0
  	for f, _ := range fs {
  		len++
  		for _, v := range validFilters {
  			if f == v {
  				cnt++
  				goodFilters[f] = fs[f]
  			}
  		}
  	}
  
  	result := true
  	if len > 0 && cnt == 0 {
  		// if no valid filters are found declare filtering request as invalid
  		result = false
  	}
  
  	return goodFilters, result
  }
  
  // requires input in format: "param1::value1|param2::value2..."
  func ParseFilters(req *http.Request, header string) (filters Filter) {
  	q := req.FormValue(header)
  	q = strings.Trim(q, "\"")
  	kvp := strings.Split(q, "|")
  	filters = make(map[string]string, len(kvp))
  
  	for i, _ := range kvp {
  		kv := strings.Split(kvp[i], "::")
  		if len(kv) == 2 {
d869bd3f2   Marko Tikvić   filtering fix
51
52
  			key, _ := url.QueryUnescape(kv[0])
  			val, _ := url.QueryUnescape(kv[1])
564ef6971   Marko Tikvić   added simple sql ...
53
54
55
56
57
58
  			filters[key] = val
  		}
  	}
  
  	return filters
  }
d3cc6a289   Marko Tikvić   < > filtering
59
  // TODO(marko): very dodgy, needs more robustness
564ef6971   Marko Tikvić   added simple sql ...
60
61
62
63
64
65
66
67
68
69
70
71
  func MakeFilterString(prefix string, filters Filter, validFilters []string) (res string, ok bool) {
  	if prefix != "" {
  		prefix += "."
  	}
  	if len(filters) == 0 {
  		return "", true
  	}
  
  	filters, ok = filters.validate(validFilters)
  	if !ok {
  		return "", ok
  	}
d3cc6a289   Marko Tikvić   < > filtering
72
  	symbol := "="
564ef6971   Marko Tikvić   added simple sql ...
73
74
75
76
77
78
  	for k, v := range filters {
  		if res != "" {
  			res += " and "
  		} else {
  			res += " where "
  		}
d3cc6a289   Marko Tikvić   < > filtering
79
80
  		c := string(v[0])
  		if c == "<" || c == ">" {
bca3975fd   Marko Tikvić   email
81
  			symbol = "" // examples: >3, >=3
d3cc6a289   Marko Tikvić   < > filtering
82
83
84
85
86
  		} else {
  			symbol = "="
  		}
  
  		res += fmt.Sprintf("%s%s %s '%s'", prefix, k, symbol, v)
564ef6971   Marko Tikvić   added simple sql ...
87
88
89
90
  	}
  
  	return res, ok
  }