github.com/jenspinney/cli@v6.42.1-0.20190207184520-7450c600020e+incompatible/cf/net/request_dumper.go (about)

     1  package net
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httputil"
     6  	"strings"
     7  	"time"
     8  
     9  	. "code.cloudfoundry.org/cli/cf/i18n"
    10  	"code.cloudfoundry.org/cli/cf/terminal"
    11  	"code.cloudfoundry.org/cli/cf/trace"
    12  )
    13  
    14  //go:generate counterfeiter . RequestDumperInterface
    15  
    16  type RequestDumperInterface interface {
    17  	DumpRequest(*http.Request)
    18  	DumpResponse(*http.Response)
    19  }
    20  
    21  type RequestDumper struct {
    22  	printer trace.Printer
    23  }
    24  
    25  func NewRequestDumper(printer trace.Printer) RequestDumper {
    26  	return RequestDumper{printer: printer}
    27  }
    28  
    29  func (p RequestDumper) DumpRequest(req *http.Request) {
    30  	shouldDisplayBody := !strings.Contains(req.Header.Get("Content-Type"), "multipart/form-data")
    31  	dumpedRequest, err := httputil.DumpRequest(req, shouldDisplayBody)
    32  	if err != nil {
    33  		p.printer.Printf(T("Error dumping request\n{{.Err}}\n", map[string]interface{}{"Err": err}))
    34  	} else {
    35  		p.printer.Printf("\n%s [%s]\n%s\n", terminal.HeaderColor(T("REQUEST:")), time.Now().Format(time.RFC3339), trace.Sanitize(string(dumpedRequest)))
    36  		if !shouldDisplayBody {
    37  			p.printer.Println(T("[MULTIPART/FORM-DATA CONTENT HIDDEN]"))
    38  		}
    39  	}
    40  }
    41  
    42  func (p RequestDumper) DumpResponse(res *http.Response) {
    43  	dumpedResponse, err := httputil.DumpResponse(res, true)
    44  	if err != nil {
    45  		p.printer.Printf(T("Error dumping response\n{{.Err}}\n", map[string]interface{}{"Err": err}))
    46  	} else {
    47  		p.printer.Printf("\n%s [%s]\n%s\n", terminal.HeaderColor(T("RESPONSE:")), time.Now().Format(time.RFC3339), trace.Sanitize(string(dumpedResponse)))
    48  	}
    49  }