A command line tool for DigitalOcean services

recorder.go 1.4KB

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