-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathmapsutil.go
265 lines (217 loc) · 5.93 KB
/
mapsutil.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package mapsutil
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httputil"
"sort"
"strings"
"time"
"github.com/miekg/dns"
"golang.org/x/exp/constraints"
extmaps "golang.org/x/exp/maps"
)
// Merge merges the inputted maps into a new one.
// Be aware: In case of duplicated keys in multiple maps,
// the one ending in the result is unknown a priori.
func Merge[K comparable, V any](maps ...map[K]V) (result map[K]V) {
result = make(map[K]V)
for _, m := range maps {
for k, v := range m {
result[k] = v
}
}
return
}
const defaultFormat = "%s"
// HTTPToMap Converts HTTP to Matcher Map
func HTTPToMap(resp *http.Response, body, headers string, duration time.Duration, format string) (m map[string]interface{}) {
m = make(map[string]interface{})
if format == "" {
format = defaultFormat
}
m[fmt.Sprintf(format, "content_length")] = resp.ContentLength
m[fmt.Sprintf(format, "status_code")] = resp.StatusCode
for k, v := range resp.Header {
k = strings.ToLower(strings.TrimSpace(strings.ReplaceAll(k, "-", "_")))
m[fmt.Sprintf(format, k)] = strings.Join(v, " ")
}
m[fmt.Sprintf(format, "all_headers")] = headers
m[fmt.Sprintf(format, "body")] = body
if r, err := httputil.DumpResponse(resp, true); err == nil {
m[fmt.Sprintf(format, "raw")] = string(r)
}
// Converts duration to seconds (floating point) for DSL syntax
m[fmt.Sprintf(format, "duration")] = duration.Seconds()
return m
}
// DNSToMap Converts DNS to Matcher Map
func DNSToMap(msg *dns.Msg, format string) (m map[string]interface{}) {
m = make(map[string]interface{})
if format == "" {
format = defaultFormat
}
m[fmt.Sprintf(format, "rcode")] = msg.Rcode
var qs string
for _, question := range msg.Question {
qs += fmt.Sprintln(question.String())
}
m[fmt.Sprintf(format, "question")] = qs
var exs string
for _, extra := range msg.Extra {
exs += fmt.Sprintln(extra.String())
}
m[fmt.Sprintf(format, "extra")] = exs
var ans string
for _, answer := range msg.Answer {
ans += fmt.Sprintln(answer.String())
}
m[fmt.Sprintf(format, "answer")] = ans
var nss string
for _, ns := range msg.Ns {
nss += fmt.Sprintln(ns.String())
}
m[fmt.Sprintf(format, "ns")] = nss
m[fmt.Sprintf(format, "raw")] = msg.String()
return m
}
// HTTPRequestToMap Converts HTTP Request to Matcher Map
func HTTPRequestToMap(req *http.Request) (map[string]interface{}, error) {
m := make(map[string]interface{})
var headers string
for k, v := range req.Header {
k = strings.ToLower(strings.TrimSpace(strings.ReplaceAll(k, "-", "_")))
vv := strings.Join(v, " ")
m[k] = strings.Join(v, " ")
headers += fmt.Sprintf("%s: %s", k, vv)
}
m["all_headers"] = headers
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
req.Body = io.NopCloser(bytes.NewBuffer(body))
m["body"] = string(body)
reqdump, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, err
}
reqdumpString := string(reqdump)
m["raw"] = reqdumpString
m["request"] = reqdumpString
return m, nil
}
// HTTPResponseToMap Converts HTTP Response to Matcher Map
func HTTPResponseToMap(resp *http.Response) (map[string]interface{}, error) {
m := make(map[string]interface{})
m["content_length"] = resp.ContentLength
m["status_code"] = resp.StatusCode
var headers string
for k, v := range resp.Header {
k = strings.ToLower(strings.TrimSpace(strings.ReplaceAll(k, "-", "_")))
vv := strings.Join(v, " ")
m[k] = vv
headers += fmt.Sprintf("%s: %s", k, vv)
}
m["all_headers"] = headers
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
resp.Body.Close()
resp.Body = io.NopCloser(bytes.NewBuffer(body))
m["body"] = string(body)
if r, err := httputil.DumpResponse(resp, true); err == nil {
responseString := string(r)
m["raw"] = responseString
m["response"] = responseString
}
return m, nil
}
// GetKeys returns the map's keys.
func GetKeys[K comparable, V any](maps ...map[K]V) []K {
var keys []K
for _, m := range maps {
keys = append(keys, extmaps.Keys(m)...)
}
return keys
}
// GetValues returns the map's values.
func GetValues[K comparable, V any](maps ...map[K]V) []V {
var values []V
for _, m := range maps {
values = append(values, extmaps.Values(m)...)
}
return values
}
// Difference returns the inputted map without the keys specified as input.
func Difference[K comparable, V any](m map[K]V, keys ...K) map[K]V {
for _, key := range keys {
delete(m, key)
}
return m
}
// Flatten takes a map and returns a new one where nested maps are replaced
// by dot-delimited keys.
func Flatten(m map[string]any, separator string) map[string]any {
if separator == "" {
separator = "."
}
o := make(map[string]any)
for k, v := range m {
switch child := v.(type) {
case map[string]any:
nm := Flatten(child, separator)
for nk, nv := range nm {
o[k+separator+nk] = nv
}
default:
o[k] = v
}
}
return o
}
// Walk a map and visit all the edge key:value pairs
func Walk(m map[string]any, callback func(k string, v any)) {
for k, v := range m {
switch child := v.(type) {
case map[string]any:
Walk(child, callback)
default:
callback(k, v)
}
}
}
// Clear the map passed as parameter
func Clear[K comparable, V any](mm ...map[K]V) {
for _, m := range mm {
extmaps.Clear(m)
}
}
// SliceToMap returns a map having as keys the elements in
// even positions and as values the elements in odd positions.
// If the number of elements is odd the default value applies.
func SliceToMap[T comparable](s []T, dflt T) map[T]T {
result := map[T]T{}
for i := 0; i < len(s); i += 2 {
if i+1 < len(s) {
result[s[i]] = s[i+1]
} else {
result[s[i]] = dflt
}
}
return result
}
// IsEmpty checks if a map is empty.
func IsEmpty[K comparable, V any](m map[K]V) bool {
return len(m) == 0
}
// GetSortedKeys returns the map's keys sorted.
func GetSortedKeys[K constraints.Ordered, V any](maps ...map[K]V) []K {
keys := GetKeys(maps...)
sort.Slice(keys, func(i, j int) bool {
return keys[i] < keys[j]
})
return keys
}