-
Notifications
You must be signed in to change notification settings - Fork 1
/
debug.go
99 lines (85 loc) · 2.39 KB
/
debug.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
package spectest
import (
"fmt"
"net/http"
"net/http/httputil"
"strings"
)
// debug is used to enable/disable debug logging
type debug struct {
enabled bool
}
// newDebug creates a new debug setting
func newDebug() *debug {
return &debug{}
}
// enable will enable debug logging
func (d *debug) enable() {
d.enabled = true
}
// isEnable returns true if debug logging is enabled
func (d *debug) isEnable() bool {
return d.enabled
}
// dumpResponse is used to dump the response.
// If debug logging is disabled, this method will do nothing.
func (d *debug) dumpRequest(req *http.Request) {
if !d.isEnable() {
return
}
requestDump, err := httputil.DumpRequest(req, true)
if err == nil {
debugLog(requestDebugPrefix(), "inbound http request", string(requestDump))
}
// TODO: handle error
}
// dumpResponse is used to dump the response.
// If debug logging is disabled, this method will do nothing.
func (d *debug) dumpResponse(res *http.Response) {
if !d.isEnable() {
return
}
responseDump, err := httputil.DumpResponse(res, true)
if err == nil {
debugLog(responseDebugPrefix(), "final response", string(responseDump))
}
// TODO: handle error
}
// duration is used to print the duration of the test.
// If debug logging is disabled, this method will do nothing.
func (d *debug) duration(interval *Interval) {
if !d.isEnable() {
return
}
fmt.Printf("Duration: %s\n", interval.Duration())
}
// mock is used to print the request and response from the mock.
func (d *debug) mock(res *http.Response, req *http.Request) {
if !d.isEnable() {
return
}
requestDump, err := httputil.DumpRequestOut(req, true)
if err == nil {
debugLog(requestDebugPrefix(), "request to mock", string(requestDump))
}
if res != nil {
responseDump, err := httputil.DumpResponse(res, true)
if err == nil {
debugLog(responseDebugPrefix(), "response from mock", string(responseDump))
}
} else {
debugLog(responseDebugPrefix(), "response from mock", "")
}
}
// debugLog is used to print debug information
func debugLog(prefix, header, msg string) {
fmt.Printf("\n%s %s\n%s\n", prefix, header, msg)
}
// requestDebugLog is used to print debug information for the request
func requestDebugPrefix() string {
return fmt.Sprintf("%s>", strings.Repeat("-", 10))
}
// responseDebugLog is used to print debug information for the response
func responseDebugPrefix() string {
return fmt.Sprintf("<%s", strings.Repeat("-", 10))
}