From 564ef69718207b6ebf7eb0897706e3019564d051 Mon Sep 17 00:00:00 2001 From: "marko.tikvic" Date: Tue, 23 Oct 2018 14:54:44 +0200 Subject: [PATCH] added simple sql filter string parser/generator --- filtering.go | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 filtering.go diff --git a/filtering.go b/filtering.go new file mode 100644 index 0000000..ec68510 --- /dev/null +++ b/filtering.go @@ -0,0 +1,76 @@ +package webutility + +import ( + "fmt" + "net/http" + "strings" +) + +type Filter map[string]string + +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 { + key := kv[0] + val := kv[1] + filters[key] = val + } + } + + return filters +} + +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 + } + + for k, v := range filters { + if res != "" { + res += " and " + } else { + res += " where " + } + res += fmt.Sprintf("%s%s = '%s'", prefix, k, v) + } + + return res, ok +} -- 1.8.1.2