-
Notifications
You must be signed in to change notification settings - Fork 0
/
collector.go
138 lines (104 loc) · 2.27 KB
/
collector.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/nqd/flat"
)
type (
stringValues map[string]string
interfaceValues map[string]interface{}
)
func (v stringValues) get(key string) string {
if val, ok := v[key]; ok {
return val
}
return ""
}
func (v interfaceValues) get(key string) string {
var result interface{}
if val, ok := v[key]; ok {
result = val
} else {
log.Println("key not found ", key)
return ""
}
return fmt.Sprintf("%v", result)
}
type collector struct {
params stringValues
resources stringValues
headers stringValues
body interfaceValues
}
func (c collector) getFromParam(key string) string {
return c.params.get(key)
}
func (c collector) getFromResource(key string) string {
return c.resources.get(key)
}
func (c collector) getFromHeader(key string) string {
return c.headers.get(key)
}
func (c collector) getFromBody(key string) string {
return c.body.get(key)
}
func (c collector) get(target string, modifier string) string {
switch target {
case TargetParams:
return c.getFromParam(modifier)
case TargetHeader:
return c.getFromHeader(modifier)
case TargetBody:
return c.getFromBody(modifier)
case TargetResource:
return c.getFromResource(modifier)
}
log.Println("no matching target found")
return ""
}
func collectRequestDetails(r *http.Request) collector {
return collector{
params: collectParams(r),
resources: collectResources(r),
headers: collectHeaders(r),
body: collectBody(r),
}
}
func collectParams(r *http.Request) stringValues {
data := stringValues{}
for key, val := range r.URL.Query() {
data[key] = val[0]
}
return data
}
func collectHeaders(r *http.Request) stringValues {
data := stringValues{}
for key, val := range r.Header {
data[key] = val[0]
}
return data
}
func collectResources(r *http.Request) stringValues {
data := stringValues{}
for key, val := range mux.Vars(r) {
data[key] = val
}
return data
}
func collectBody(r *http.Request) interfaceValues {
var (
request = interfaceValues{}
data interfaceValues
)
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
log.Println(err)
}
data, err := flat.Flatten(request, nil)
if err != nil {
log.Println(err)
}
return data
}