forked from jfyne/live
-
Notifications
You must be signed in to change notification settings - Fork 0
/
params.go
93 lines (86 loc) · 1.47 KB
/
params.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
90
91
92
93
package live
import (
"net/http"
"strconv"
)
// Params event params.
type Params map[string]interface{}
// String helper to get a string from the params.
func (p Params) String(key string) string {
v, ok := p[key]
if !ok {
return ""
}
out, ok := v.(string)
if !ok {
return ""
}
return out
}
// Checkbox helper to return a boolean from params referring to
// a checkbox input.
func (p Params) Checkbox(key string) bool {
v, ok := p[key]
if !ok {
return false
}
out, ok := v.(string)
if !ok {
return false
}
if out == "on" {
return true
}
return false
}
// Int helper to return and int from the params.
func (p Params) Int(key string) int {
v, ok := p[key]
if !ok {
return 0
}
switch out := v.(type) {
case int:
return out
case string:
i, err := strconv.Atoi(out)
if err != nil {
return 0
}
return i
}
return 0
}
// Float32 helper to return a float32 from the params.
func (p Params) Float32(key string) float32 {
v, ok := p[key]
if !ok {
return 0.0
}
switch out := v.(type) {
case float32:
return out
case float64:
return float32(out)
case string:
f, err := strconv.ParseFloat(out, 32)
if err != nil {
return 0.0
}
return float32(f)
}
return 0.0
}
// NewParamsFromRequest helper to generate Params from an http request.
func NewParamsFromRequest(r *http.Request) Params {
out := Params{}
values := r.URL.Query()
for k, v := range values {
if len(v) == 1 {
out[k] = v[0]
} else {
out[k] = v
}
}
return out
}