/
ghttp_client_dump.go
86 lines (76 loc) · 2.06 KB
/
ghttp_client_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
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
// Copyright 2020 gf Author(https://github.com/yyf330/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/yyf330/gf.
package ghttp
import (
"fmt"
"github.com/yyf330/gf/internal/utils"
"io/ioutil"
"net/http"
"net/http/httputil"
"github.com/yyf330/gf/util/gconv"
)
// dumpTextFormat is the format of the dumped raw string
const dumpTextFormat = `+---------------------------------------------+
| %s |
+---------------------------------------------+
%s
%s
`
// getResponseBody returns the text of the response body.
func getResponseBody(res *http.Response) string {
if res.Body == nil {
return ""
}
bodyContent, _ := ioutil.ReadAll(res.Body)
res.Body = utils.NewReadCloser(bodyContent, true)
return gconv.UnsafeBytesToStr(bodyContent)
}
// RawRequest returns the raw content of the request.
func (r *ClientResponse) RawRequest() string {
// ClientResponse can be nil.
if r == nil {
return ""
}
if r.request == nil {
return ""
}
// DumpRequestOut writes more request headers than DumpRequest, such as User-Agent.
bs, err := httputil.DumpRequestOut(r.request, false)
if err != nil {
return ""
}
return fmt.Sprintf(
dumpTextFormat,
"REQUEST ",
gconv.UnsafeBytesToStr(bs),
r.requestBody,
)
}
// RawResponse returns the raw content of the response.
func (r *ClientResponse) RawResponse() string {
// ClientResponse can be nil.
if r == nil || r.Response == nil {
return ""
}
bs, err := httputil.DumpResponse(r.Response, false)
if err != nil {
return ""
}
return fmt.Sprintf(
dumpTextFormat,
"RESPONSE",
gconv.UnsafeBytesToStr(bs),
getResponseBody(r.Response),
)
}
// Raw returns the raw text of the request and the response.
func (r *ClientResponse) Raw() string {
return fmt.Sprintf("%s\n%s", r.RawRequest(), r.RawResponse())
}
// RawDump outputs the raw text of the request and the response to stdout.
func (r *ClientResponse) RawDump() {
fmt.Println(r.Raw())
}