-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
64 lines (55 loc) · 1.31 KB
/
helpers.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
package goober
import (
"encoding/json"
"io"
"net/http"
"strings"
)
func extractParams(pattern, path string) map[string]string {
params := make(map[string]string)
patternParts := strings.Split(pattern, "/")
pathParts := strings.Split(path, "/")
for i, part := range patternParts {
if strings.HasPrefix(part, ":") && i < len(pathParts) {
key := strings.TrimPrefix(part, ":")
params[key] = pathParts[i]
}
}
return params
}
func extractHeaders(r *http.Request) map[string]string {
headers := make(map[string]string)
for name, values := range r.Header {
headers[name] = values[0]
}
return headers
}
func extractQueryParams(r *http.Request) map[string]string {
query := make(map[string]string)
for name, values := range r.URL.Query() {
query[name] = values[0]
}
return query
}
func extractBody(r *http.Request) map[string]interface{} {
body := make(map[string]interface{})
if r.Body == nil {
return body
}
defer r.Body.Close()
bodyBytes, err := io.ReadAll(r.Body)
if err != nil || len(bodyBytes) == 0 {
return body
}
if err := json.Unmarshal(bodyBytes, &body); err != nil {
return body
}
return body
}
func extractCookies(r *http.Request) map[string]string {
cookies := make(map[string]string)
for _, cookie := range r.Cookies() {
cookies[cookie.Name] = cookie.Value
}
return cookies
}