-
Notifications
You must be signed in to change notification settings - Fork 13
/
context.go
118 lines (92 loc) · 2.43 KB
/
context.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package mux
import (
"context"
"net/http"
"net/url"
"strings"
)
type contextKey int
const (
queriesKey contextKey = iota
routeKey
varsKey
)
// GetQueries returns the query variables for the current request.
func GetQueries(r *http.Request) queries {
if rv := contextGet(r, queriesKey); rv != nil {
return rv.(queries)
}
return nil
}
// CurrentRoute returns the matched route for the current request.
// This only works when called inside the handler of the matched route
// because the matched route is stored in the request context which is cleared
// after the handler returns
func CurrentRoute(r *http.Request) RouteInterface {
if rv := contextGet(r, routeKey); rv != nil {
return rv.(RouteInterface)
}
return nil
}
func AddQueries(r *http.Request) *http.Request {
queries, err := extractQueries(r)
if err != nil || 0 == queries.Count() {
return r
}
return contextSet(r, queriesKey, queries)
}
func AddCurrentRoute(r *http.Request, val interface{}) *http.Request {
return contextSet(r, routeKey, val)
}
// GetVars returns the route variables for the current request, if any.
func GetVars(r *http.Request) Vars {
if rv := contextGet(r, varsKey); rv != nil {
return rv.(Vars)
}
return nil
}
func AddVars(r *http.Request, val interface{}) *http.Request {
return contextSet(r, varsKey, val)
}
func contextGet(r *http.Request, key interface{}) interface{} {
return r.Context().Value(key)
}
func contextSet(r *http.Request, key, val interface{}) *http.Request {
if val == nil {
return r
}
return r.WithContext(context.WithValue(r.Context(), key, val))
}
type queries map[string][]string
// Get return the key value, of the current *http.Request queries
func (q queries) Get(key string) []string {
if value, found := q[key]; found {
return value
}
return make([]string, 0)
}
// Get returns all queries of the current *http.Request queries
func (q queries) GetAll() map[string][]string {
return q
}
// Count returns count of the current *http.Request queries
func (q queries) Count() int {
return len(q)
}
func extractQueries(req *http.Request) (queries, error) {
queriesRaw, err := url.ParseQuery(req.URL.RawQuery)
if err != nil {
return nil, err
}
queries := queries(map[string][]string{})
if 0 == len(queriesRaw) {
return queries, nil
}
for k, v := range queriesRaw {
for _, item := range v {
values := strings.Split(item, ",")
queries[k] = append(queries[k], values...)
}
}
return queries, nil
}