-
Notifications
You must be signed in to change notification settings - Fork 0
/
printer.go
100 lines (82 loc) · 2.23 KB
/
printer.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
package httpexpect
import (
"net/http"
"net/http/httputil"
"strings"
"time"
"github.com/moul/http2curl"
)
// CompactPrinter implements Printer. It prints requests in compact form.
type CompactPrinter struct {
logger Logger
}
// NewCompactPrinter returns a new CompactPrinter given a logger.
func NewCompactPrinter(logger Logger) CompactPrinter {
return CompactPrinter{logger}
}
// Request implements Printer.Request.
func (p CompactPrinter) Request(req *http.Request) {
if req != nil {
p.logger.Logf("%s %s", req.Method, req.URL)
}
}
// Response implements Printer.Response.
func (CompactPrinter) Response(*http.Response, time.Duration) {
}
// DebugPrinter implements Printer. Uses net/http/httputil to dump
// both requests and responses.
type DebugPrinter struct {
logger Logger
body bool
}
// NewDebugPrinter returns a new DebugPrinter given a logger and body
// flag. If body is true, request and response body is also printed.
func NewDebugPrinter(logger Logger, body bool) DebugPrinter {
return DebugPrinter{logger, body}
}
// Request implements Printer.Request.
func (p DebugPrinter) Request(req *http.Request) {
if req == nil {
return
}
dump, err := httputil.DumpRequest(req, p.body)
if err != nil {
panic(err)
}
p.logger.Logf("%s", dump)
}
// Response implements Printer.Response.
func (p DebugPrinter) Response(resp *http.Response, duration time.Duration) {
if resp == nil {
return
}
dump, err := httputil.DumpResponse(resp, p.body)
if err != nil {
panic(err)
}
text := strings.Replace(string(dump), "\r\n", "\n", -1)
lines := strings.SplitN(text, "\n", 2)
p.logger.Logf("%s %s\n%s", lines[0], duration, lines[1])
}
// CurlPrinter implements Printer. Uses http2curl to dump requests as
// curl commands.
type CurlPrinter struct {
logger Logger
}
// NewCurlPrinter returns a new CurlPrinter given a logger.
func NewCurlPrinter(logger Logger) CurlPrinter {
return CurlPrinter{logger}
}
// Request implements Printer.Request.
func (p CurlPrinter) Request(req *http.Request) {
if req != nil {
cmd, err := http2curl.GetCurlCommand(req)
if err != nil {
panic(err)
}
p.logger.Logf("%s", cmd.String())
}
}
// Response implements Printer.Response.
func (CurlPrinter) Response(*http.Response, time.Duration) {
}