forked from smarty-archives/httpunit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdump.go
53 lines (45 loc) · 1.26 KB
/
dump.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
package httpunit
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"net/http/httputil"
"strings"
"testing"
)
type DumpHandler struct {
t T
inner http.Handler
dump *bytes.Buffer
}
func NewDumpHandler(t T, inner http.Handler) *DumpHandler {
return &DumpHandler{
t: t,
inner: inner,
dump: new(bytes.Buffer),
}
}
func (this *DumpHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {
this.dumpRequest(request)
this.inner.ServeHTTP(response, request)
this.dumpResponse(response.(*httptest.ResponseRecorder).Result())
}
func (this *DumpHandler) dumpRequest(request *http.Request) {
requestDump, _ := httputil.DumpRequest(request, true)
fmt.Fprintf(this.dump, "REQUEST DUMP:\n%s\n\n", formatDump(">", string(requestDump)))
}
func (this *DumpHandler) dumpResponse(response *http.Response) {
responseDump, _ := httputil.DumpResponse(response, true)
fmt.Fprintf(this.dump, "RESPONSE DUMP:\n%s\n\n", formatDump("<", string(responseDump)))
}
func formatDump(prefix, dump string) string {
prefix = "\n" + prefix + " "
lines := strings.Split(strings.TrimSpace(dump), "\n")
return prefix + strings.Join(lines, prefix)
}
func (this *DumpHandler) Teardown() {
if testing.Verbose() || this.t.Failed() {
this.t.Log("\n"+this.dump.String())
}
}