github.com/jenkins-x/jx/v2@v2.1.155/pkg/util/trace/tracer.go (about) 1 package trace 2 3 import ( 4 "fmt" 5 "net/http" 6 "net/http/httputil" 7 "os" 8 "regexp" 9 ) 10 11 // Tracer implements http.RoundTripper. It prints each request and 12 // response/error to os.Stderr. 13 type Tracer struct { 14 http.RoundTripper 15 } 16 17 // RoundTrip calls the nested RoundTripper while printing each request and 18 // response/error to os.Stderr on either side of the nested call. 19 func (t *Tracer) RoundTrip(req *http.Request) (*http.Response, error) { 20 // Dump the request to os.Stderr. 21 b, err := httputil.DumpRequestOut(req, true) 22 if err != nil { 23 return nil, err 24 } 25 os.Stderr.Write(t.sanitize(b)) 26 os.Stderr.Write([]byte{'\n'}) 27 28 // Call the nested RoundTripper. 29 resp, err := t.RoundTripper.RoundTrip(req) 30 31 // If an error was returned, dump it to os.Stderr. 32 if err != nil { 33 fmt.Fprintln(os.Stderr, err) 34 return resp, err 35 } 36 37 // Dump the response to os.Stderr. 38 b, err = httputil.DumpResponse(resp, req.URL.Query().Get("watch") != "true") 39 if err != nil { 40 return nil, err 41 } 42 os.Stderr.Write(b) 43 os.Stderr.Write([]byte("---")) 44 os.Stderr.Write([]byte{'\n'}) 45 46 return resp, err 47 } 48 49 func (t *Tracer) sanitize(raw []byte) []byte { 50 s := string(raw) 51 regExp := regexp.MustCompile("Authorization: Bearer .*\n") 52 s = regExp.ReplaceAllString(s, "Authorization: Bearer xxx\n") 53 return []byte(s) 54 }