improve dump feature for ghttp.Request

This commit is contained in:
John 2020-06-09 20:46:04 +08:00
parent 9b330adc1d
commit 0290de2360
3 changed files with 7 additions and 18 deletions

View File

@ -18,22 +18,12 @@ import (
// dumpTextFormat is the format of the dumped raw string // dumpTextFormat is the format of the dumped raw string
const dumpTextFormat = `+---------------------------------------------+ const dumpTextFormat = `+---------------------------------------------+
| %s | | %s |
+---------------------------------------------+ +---------------------------------------------+
%s %s
%s %s
` `
// getRequestBody returns the raw text of the request body.
func getRequestBody(req *http.Request) string {
if req.Body == nil {
return ""
}
bodyContent, _ := ioutil.ReadAll(req.Body)
req.Body = utils.NewReadCloser(bodyContent, true)
return gconv.UnsafeBytesToStr(bodyContent)
}
// getResponseBody returns the text of the response body. // getResponseBody returns the text of the response body.
func getResponseBody(res *http.Response) string { func getResponseBody(res *http.Response) string {
if res.Body == nil { if res.Body == nil {
@ -60,9 +50,9 @@ func (r *ClientResponse) RawRequest() string {
} }
return fmt.Sprintf( return fmt.Sprintf(
dumpTextFormat, dumpTextFormat,
"REQUEST ", "REQUEST",
gconv.UnsafeBytesToStr(bs), gconv.UnsafeBytesToStr(bs),
getRequestBody(r.request), r.requestBody,
) )
} }

View File

@ -223,10 +223,8 @@ func (c *Client) DoRequest(method, url string, data ...interface{}) (resp *Clien
// The request body can be reused for dumping // The request body can be reused for dumping
// raw HTTP request-response procedure. // raw HTTP request-response procedure.
reqBodyContent, _ := ioutil.ReadAll(req.Body) reqBodyContent, _ := ioutil.ReadAll(req.Body)
resp.requestBody = reqBodyContent
req.Body = utils.NewReadCloser(reqBodyContent, false) req.Body = utils.NewReadCloser(reqBodyContent, false)
defer func() {
resp.request.Body = utils.NewReadCloser(reqBodyContent, true)
}()
for { for {
if resp.Response, err = c.Do(req); err != nil { if resp.Response, err = c.Do(req); err != nil {
if c.retryCount > 0 { if c.retryCount > 0 {

View File

@ -16,8 +16,9 @@ import (
// ClientResponse is the struct for client request response. // ClientResponse is the struct for client request response.
type ClientResponse struct { type ClientResponse struct {
*http.Response *http.Response
request *http.Request request *http.Request
cookies map[string]string requestBody []byte
cookies map[string]string
} }
// initCookie initializes the cookie map attribute of ClientResponse. // initCookie initializes the cookie map attribute of ClientResponse.