1/* 2Copyright 2018 The Doctl Authors All rights reserved. 3Licensed under the Apache License, Version 2.0 (the "License"); 4you may not use this file except in compliance with the License. 5You may obtain a copy of the License at 6 http://www.apache.org/licenses/LICENSE-2.0 7Unless required by applicable law or agreed to in writing, software 8distributed under the License is distributed on an "AS IS" BASIS, 9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10See the License for the specific language governing permissions and 11limitations under the License. 12*/ 13 14package doctl 15 16import ( 17 "fmt" 18 "net/http" 19 "net/http/httputil" 20) 21 22// recorder traces http connections. It sends the output to a request and 23// response channels. 24type recorder struct { 25 wrap http.RoundTripper 26 req chan string 27 resp chan string 28} 29 30func newRecorder(transport http.RoundTripper) *recorder { 31 return &recorder{ 32 wrap: transport, 33 req: make(chan string), 34 resp: make(chan string), 35 } 36} 37 38func (rec *recorder) RoundTrip(req *http.Request) (*http.Response, error) { 39 reqBytes, err := httputil.DumpRequestOut(req, true) 40 if err != nil { 41 return nil, fmt.Errorf("transport.Recorder: dumping request, %v", err) 42 } 43 rec.req <- string(reqBytes) 44 45 resp, rerr := rec.wrap.RoundTrip(req) 46 if rerr != nil { 47 return nil, rerr 48 } 49 50 respBytes, err := httputil.DumpResponse(resp, true) 51 if err != nil { 52 return nil, fmt.Errorf("transport.Recorder: dumping response, %v", err) 53 } 54 rec.resp <- string(respBytes) 55 56 return resp, nil 57} 58