github.com/gogf/gf@v1.16.9/net/ghttp/internal/client/client_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/gogf/gf.
     6  
     7  package client
     8  
     9  import (
    10  	"fmt"
    11  	"io/ioutil"
    12  	"net/http"
    13  	"net/http/httputil"
    14  
    15  	"github.com/gogf/gf/internal/utils"
    16  )
    17  
    18  // dumpTextFormat is the format of the dumped raw string
    19  const dumpTextFormat = `+---------------------------------------------+
    20  |                   %s                  |
    21  +---------------------------------------------+
    22  %s
    23  %s
    24  `
    25  
    26  // getResponseBody returns the text of the response body.
    27  func getResponseBody(res *http.Response) string {
    28  	if res.Body == nil {
    29  		return ""
    30  	}
    31  	bodyContent, _ := ioutil.ReadAll(res.Body)
    32  	res.Body = utils.NewReadCloser(bodyContent, true)
    33  	return string(bodyContent)
    34  }
    35  
    36  // RawRequest returns the raw content of the request.
    37  func (r *Response) RawRequest() string {
    38  	// Response can be nil.
    39  	if r == nil {
    40  		return ""
    41  	}
    42  	if r.request == nil {
    43  		return ""
    44  	}
    45  	// DumpRequestOut writes more request headers than DumpRequest, such as User-Agent.
    46  	bs, err := httputil.DumpRequestOut(r.request, false)
    47  	if err != nil {
    48  		return ""
    49  	}
    50  	return fmt.Sprintf(
    51  		dumpTextFormat,
    52  		"REQUEST ",
    53  		string(bs),
    54  		r.requestBody,
    55  	)
    56  }
    57  
    58  // RawResponse returns the raw content of the response.
    59  func (r *Response) RawResponse() string {
    60  	// Response might be nil.
    61  	if r == nil || r.Response == nil {
    62  		return ""
    63  	}
    64  	bs, err := httputil.DumpResponse(r.Response, false)
    65  	if err != nil {
    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  }