forked from nbari/violetear
-
Notifications
You must be signed in to change notification settings - Fork 0
/
params.go
80 lines (74 loc) · 1.71 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
package violetear
import (
"net/http"
)
// Params string/interface map used with context
type Params map[string]interface{}
// Add param to Params
func (p Params) Add(k, v string) {
if param, ok := p[k]; ok {
switch param.(type) {
case string:
param = []string{param.(string), v}
case []string:
param = append(param.([]string), v)
}
p[k] = param
} else {
p[k] = v
}
}
// GetParam returns a value for the parameter set in path
// When having duplicate params pass the index as the last argument to
// retrieve the desired value.
func GetParam(name string, r *http.Request, index ...int) string {
if params := r.Context().Value(ParamsKey); params != nil {
params := params.(Params)
if name != "*" {
name = ":" + name
}
if param := params[name]; param != nil {
switch param := param.(type) {
case []string:
if len(index) > 0 {
if index[0] < len(param) {
return param[index[0]]
}
return ""
}
return param[0]
default:
return param.(string)
}
}
}
return ""
}
// GetParams returns param or params in a []string
func GetParams(name string, r *http.Request) []string {
if params := r.Context().Value(ParamsKey); params != nil {
params := params.(Params)
if name != "*" {
name = ":" + name
}
if param := params[name]; param != nil {
switch param := param.(type) {
case []string:
return param
default:
return []string{param.(string)}
}
}
}
return []string{}
}
// GetRouteName return the name of the route
func GetRouteName(r *http.Request) string {
if params := r.Context().Value(ParamsKey); params != nil {
params := params.(Params)
if param := params["rname"]; param != nil {
return param.(string)
}
}
return ""
}