-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbase.go
More file actions
57 lines (47 loc) · 1.2 KB
/
base.go
File metadata and controls
57 lines (47 loc) · 1.2 KB
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
package main
import (
"strconv"
"strings"
)
// Base struct for models that whan to user complex query schema
type Base struct {
Query map[string][]string `sql:"-" json:",omitempty"`
}
var (
queryIdentifiers = map[string]string{"gte": ">=", "gt": ">", "lte": "<=", "lt": "<", "eq": "="}
paramDelimiter = "|"
)
func (b *Base) BuildQuery() string {
var query string
// identifierKey = gte, identifierValue = >=
for identifierKey, identifierValue := range queryIdentifiers {
// val = [quantity|200]
if queryWithKeyValues, ok := b.Query[identifierKey]; ok {
// currQueryValue = quantity|200
for _, currQueryValue := range queryWithKeyValues {
// splitted = [quantity 200]
splitted := strings.Split(currQueryValue, paramDelimiter)
if len(splitted) != 2 {
continue
}
if query != "" {
query += " and "
}
if isNumber(splitted[1]) {
query += splitted[0] + identifierValue + splitted[1]
} else {
query += splitted[0] + identifierValue + "'" + splitted[1] + "'"
}
}
}
}
return query
}
func isNumber(s string) bool {
_, err1 := strconv.Atoi(s)
_, err2 := strconv.ParseFloat(s, 64)
if err1 == nil && err2 == nil {
return true
}
return false
}