-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract.go
97 lines (71 loc) · 1.61 KB
/
extract.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
package liberlogger
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"reflect"
"github.com/kataras/compress"
"github.com/rs/zerolog"
)
func parseHeaders(headers map[string][]string) map[string]string {
newHeaders := map[string]string{}
for key, header := range headers {
newHeaders[key] = header[0]
}
return newHeaders
}
func extractBody(request interface{}, parseTo interface{}) error {
var bodyBytes []byte
typeParse := reflect.ValueOf(parseTo)
if typeParse.Kind() != reflect.Ptr {
return errors.New("parseTo must be a pointer")
}
switch request := request.(type) {
case *http.Request:
var err error
if request.Body == nil {
return nil
}
bodyBytes, err = io.ReadAll(request.Body)
if err != nil {
return err
}
defer request.Body.Close()
request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
case *http.Response:
var err error
if request.Body == nil {
return nil
}
if request.Header.Get("Content-Encoding") == "deflate" {
reader, err := compress.NewReader(request.Body, compress.DEFLATE)
if err != nil {
return err
}
defer reader.Close()
request.Body = reader
}
bodyBytes, err = io.ReadAll(request.Body)
if err != nil {
return err
}
defer request.Body.Close()
request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
default:
return errors.New("request is not a valid type")
}
if len(bodyBytes) == 0 {
return nil
}
return json.Unmarshal(bodyBytes, parseTo)
}
func ignoreRedacted() bool {
zerologLevel := zerolog.GlobalLevel()
switch zerologLevel {
case zerolog.DebugLevel:
return true
}
return false
}