forked from TF2Stadium/Helen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filters.go
89 lines (79 loc) · 2.25 KB
/
filters.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
package controllerhelpers
import (
"strings"
"github.com/TF2Stadium/Helen/helpers"
"github.com/bitly/go-simplejson"
)
func AuthFilter(socketid string, f func(string) string) func(string) string {
return func(data string) string {
if !IsLoggedInSocket(socketid) {
bytes, _ := BuildFailureJSON("Player isn't logged in.", -4).Encode()
return string(bytes)
}
return f(data)
}
}
func JsonParamFilter(f func(*simplejson.Json) string) func(string) string {
return func(data string) string {
js, err := simplejson.NewFromReader(strings.NewReader(data))
if err != nil {
bytes, _ := BuildFailureJSON("Malformed JSON syntax.", 0).Encode()
return string(bytes)
}
return f(js)
}
}
type Param struct {
Type ParamType
Default interface{}
}
type ParamType int
const (
PTypeInt ParamType = iota
PTypeString ParamType = iota
PTypeBool ParamType = iota
PTypeFloat ParamType = iota
)
func JsonVerifiedFilter(p map[string]Param, f func(*simplejson.Json) string) func(string) string {
return JsonParamFilter(func(js *simplejson.Json) string {
for name, paramtype := range p {
switch paramtype.Type {
case PTypeInt:
_, err := js.Get(name).Int()
if err != nil && paramtype.Default == nil {
bytes, _ := BuildMissingArgJSON(name).Encode()
return string(bytes)
} else if err != nil {
js.Set(name, paramtype.Default.(int))
}
case PTypeString:
_, err := js.Get(name).String()
if err != nil && paramtype.Default == nil {
bytes, _ := BuildMissingArgJSON(name).Encode()
return string(bytes)
} else if err != nil {
js.Set(name, paramtype.Default.(string))
}
case PTypeBool:
_, err := js.Get(name).Bool()
if err != nil && paramtype.Default == nil {
bytes, _ := BuildMissingArgJSON(name).Encode()
return string(bytes)
} else if err != nil {
js.Set(name, paramtype.Default.(bool))
}
case PTypeFloat:
_, err := js.Get(name).Float64()
if err != nil && paramtype.Default == nil {
bytes, _ := BuildMissingArgJSON(name).Encode()
return string(bytes)
} else if err != nil {
js.Set(name, paramtype.Default.(float64))
}
default:
helpers.Logger.Panicf("Invalid type as parameter type for %s: %d", name, paramtype)
}
}
return f(js)
})
}