-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathresponse.go
65 lines (55 loc) · 1.53 KB
/
response.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
package treblle
import (
"encoding/json"
"fmt"
"net/http/httptest"
"time"
)
type ResponseInfo struct {
Headers json.RawMessage `json:"headers"`
Code int `json:"code"`
Size int `json:"size"`
LoadTime float64 `json:"load_time"`
Body json.RawMessage `json:"body"`
Errors []ErrorInfo `json:"errors"`
}
type ErrorInfo struct {
Source string `json:"source"`
Type string `json:"type"`
Message string `json:"message"`
File string `json:"file"`
Line int `json:"line"`
}
// Extract information from the response recorder
func getResponseInfo(response *httptest.ResponseRecorder, startTime time.Time) ResponseInfo {
defer dontPanic()
responseBytes := response.Body.Bytes()
errInfo := ErrorInfo{}
var body json.RawMessage
err := json.Unmarshal(responseBytes, &body)
if err != nil {
errInfo.Message = err.Error()
}
headers := make(map[string]string)
for k := range response.Header() {
headers[k] = response.Header().Get(k)
}
re := ResponseInfo{
Code: response.Code,
Size: len(responseBytes),
LoadTime: float64(time.Since(startTime).Microseconds()),
Errors: []ErrorInfo{},
}
bodyJson, _ := json.Marshal(body)
sanitizedBody, _ := getMaskedJSON(bodyJson)
re.Body = sanitizedBody
headersJson, _ := json.Marshal(headers)
sanitizedHeaders, _ := getMaskedJSON(headersJson)
re.Headers = sanitizedHeaders
var jsonData interface{}
err = json.Unmarshal(sanitizedHeaders, &jsonData)
if err != nil {
fmt.Println("Error parsing raw message:", err)
}
return re
}