github.com/wangyougui/gf/v2@v2.6.5/net/gclient/gclient_dump.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gclient 8 9 import ( 10 "fmt" 11 "io" 12 "net/http" 13 "net/http/httputil" 14 15 "github.com/wangyougui/gf/v2/internal/intlog" 16 "github.com/wangyougui/gf/v2/internal/utils" 17 ) 18 19 // dumpTextFormat is the format of the dumped raw string 20 const dumpTextFormat = `+---------------------------------------------+ 21 | %s | 22 +---------------------------------------------+ 23 %s 24 %s 25 ` 26 27 // getResponseBody returns the text of the response body. 28 func getResponseBody(res *http.Response) string { 29 if res.Body == nil { 30 return "" 31 } 32 bodyContent, _ := io.ReadAll(res.Body) 33 res.Body = utils.NewReadCloser(bodyContent, true) 34 return string(bodyContent) 35 } 36 37 // RawRequest returns the raw content of the request. 38 func (r *Response) RawRequest() string { 39 // Response can be nil. 40 if r == nil || r.request == nil { 41 return "" 42 } 43 // DumpRequestOut writes more request headers than DumpRequest, such as User-Agent. 44 bs, err := httputil.DumpRequestOut(r.request, false) 45 if err != nil { 46 intlog.Errorf(r.request.Context(), `%+v`, err) 47 return "" 48 } 49 return fmt.Sprintf( 50 dumpTextFormat, 51 "REQUEST ", 52 string(bs), 53 r.requestBody, 54 ) 55 } 56 57 // RawResponse returns the raw content of the response. 58 func (r *Response) RawResponse() string { 59 // Response might be nil. 60 if r == nil || r.Response == nil { 61 return "" 62 } 63 bs, err := httputil.DumpResponse(r.Response, false) 64 if err != nil { 65 intlog.Errorf(r.request.Context(), `%+v`, err) 66 return "" 67 } 68 69 return fmt.Sprintf( 70 dumpTextFormat, 71 "RESPONSE", 72 string(bs), 73 getResponseBody(r.Response), 74 ) 75 } 76 77 // Raw returns the raw text of the request and the response. 78 func (r *Response) Raw() string { 79 return fmt.Sprintf("%s\n%s", r.RawRequest(), r.RawResponse()) 80 } 81 82 // RawDump outputs the raw text of the request and the response to stdout. 83 func (r *Response) RawDump() { 84 fmt.Println(r.Raw()) 85 }