/
urlquery.go
74 lines (61 loc) · 1.58 KB
/
urlquery.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
package easy_middleware
import (
"context"
"net/http"
"net/url"
"strings"
)
// URLQueryKey is the context key for the URL Query
const URLQueryKey contextKey = "urlquery"
// URLQuery is a middleware to parse the URL Query parameters just once,
// and store the resulting url.Values in the context.
func URLQuery() Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q, err := extractURLQueries(r)
if err != nil {
r = r.WithContext(context.WithValue(r.Context(), URLQueryKey, err))
} else {
r = r.WithContext(context.WithValue(r.Context(), URLQueryKey, q))
}
h.ServeHTTP(w, r)
})
}
}
func extractURLQueries(req *http.Request) (*Queries, error) {
queriesRaw, err := url.ParseQuery(req.URL.RawQuery)
if err != nil {
return nil, err
}
queries := &Queries{
C:make(map[string][]string),
}
if 0 == len(queriesRaw) {
return queries, nil
}
for k, v := range queriesRaw {
for _, item := range v {
values := strings.Split(item, ",")
queries.C[k] = append(queries.C[k], values...)
}
}
return queries, nil
}
type Queries struct {
C 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.C[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.C
}
// Count returns count of the current *http.Request queries
func (q Queries) Count() int {
return len(q.C)
}