gf/net/gclient/gclient_dump.go

86 lines
2.1 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). 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/gogf/gf.
package gclient
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
2021-11-13 23:23:55 +08:00
"github.com/gogf/gf/v2/internal/intlog"
2021-11-13 23:23:55 +08:00
"github.com/gogf/gf/v2/internal/utils"
)
2020-04-11 12:16:53 +08:00
// dumpTextFormat is the format of the dumped raw string
const dumpTextFormat = `+---------------------------------------------+
2020-11-12 18:57:18 +08:00
| %s |
+---------------------------------------------+
%s
%s
`
2020-04-11 12:16:53 +08:00
// 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 string(bodyContent)
}
// RawRequest returns the raw content of the request.
2021-01-25 14:54:38 +08:00
func (r *Response) RawRequest() string {
// Response can be nil.
if r == nil || r.request == nil {
return ""
}
2020-04-11 12:16:53 +08:00
// DumpRequestOut writes more request headers than DumpRequest, such as User-Agent.
bs, err := httputil.DumpRequestOut(r.request, false)
if err != nil {
intlog.Errorf(r.request.Context(), `%+v`, err)
return ""
}
return fmt.Sprintf(
dumpTextFormat,
2020-11-12 18:57:18 +08:00
"REQUEST ",
string(bs),
2020-06-09 20:46:04 +08:00
r.requestBody,
)
}
// RawResponse returns the raw content of the response.
2021-01-25 14:54:38 +08:00
func (r *Response) RawResponse() string {
// Response might be nil.
if r == nil || r.Response == nil {
return ""
}
bs, err := httputil.DumpResponse(r.Response, false)
if err != nil {
intlog.Errorf(r.request.Context(), `%+v`, err)
return ""
}
return fmt.Sprintf(
dumpTextFormat,
"RESPONSE",
string(bs),
getResponseBody(r.Response),
)
}
2020-04-11 12:16:53 +08:00
// Raw returns the raw text of the request and the response.
2021-01-25 14:54:38 +08:00
func (r *Response) 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.
2021-01-25 14:54:38 +08:00
func (r *Response) RawDump() {
fmt.Println(r.Raw())
}