github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/rest/util.go (about)

     1  package rest
     2  
     3  import (
     4  	"io"
     5  	"io/ioutil"
     6  	"log"
     7  	"net/http"
     8  	"net/http/httputil"
     9  
    10  	"github.com/bingoohuang/gg/pkg/ss"
    11  )
    12  
    13  func LogResponse(r *http.Response, verbose string) {
    14  	if r != nil && ss.Contains(verbose, "rsp", "all") {
    15  		if dump, err := httputil.DumpResponse(r, true); err != nil {
    16  			log.Printf("E! Failed to dump response: %v", err)
    17  		} else {
    18  			log.Printf("Dumped response: %s", dump)
    19  		}
    20  	}
    21  }
    22  
    23  func LogRequest(r *http.Request, verbose string) {
    24  	if r != nil && ss.Contains(verbose, "req", "all") {
    25  		if dump, err := httputil.DumpRequest(r, true); err != nil {
    26  			log.Printf("Failed to dump request: %v", err)
    27  		} else {
    28  			log.Printf("Dumped request: %s", dump)
    29  		}
    30  	}
    31  }
    32  
    33  func ReadCloseBody(r *http.Response) ([]byte, error) {
    34  	if r == nil {
    35  		return nil, nil
    36  	}
    37  	if r.Body == nil {
    38  		return nil, nil
    39  	}
    40  
    41  	data, err := ioutil.ReadAll(r.Body)
    42  	r.Body.Close()
    43  
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	return data, nil
    49  }
    50  
    51  func DiscardCloseBody(r *http.Response) error {
    52  	if r == nil {
    53  		return nil
    54  	}
    55  	if r.Body == nil {
    56  		return nil
    57  	}
    58  	_, err := io.Copy(io.Discard, r.Body)
    59  	r.Body.Close()
    60  	return err
    61  }