Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

87 linhas
1.7 KiB

  1. // Copyright 2017 Google LLC
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "net/http"
  21. "os"
  22. )
  23. type logTransport struct {
  24. rt http.RoundTripper
  25. }
  26. func (t *logTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  27. var buf bytes.Buffer
  28. os.Stdout.Write([]byte("\n[request]\n"))
  29. if req.Body != nil {
  30. req.Body = ioutil.NopCloser(&readButCopy{req.Body, &buf})
  31. }
  32. req.Write(os.Stdout)
  33. if req.Body != nil {
  34. req.Body = ioutil.NopCloser(&buf)
  35. }
  36. os.Stdout.Write([]byte("\n[/request]\n"))
  37. res, err := t.rt.RoundTrip(req)
  38. fmt.Printf("[response]\n")
  39. if err != nil {
  40. fmt.Printf("ERROR: %v", err)
  41. } else {
  42. body := res.Body
  43. res.Body = nil
  44. res.Write(os.Stdout)
  45. if body != nil {
  46. res.Body = ioutil.NopCloser(&echoAsRead{body})
  47. }
  48. }
  49. return res, err
  50. }
  51. type echoAsRead struct {
  52. src io.Reader
  53. }
  54. func (r *echoAsRead) Read(p []byte) (int, error) {
  55. n, err := r.src.Read(p)
  56. if n > 0 {
  57. os.Stdout.Write(p[:n])
  58. }
  59. if err == io.EOF {
  60. fmt.Printf("\n[/response]\n")
  61. }
  62. return n, err
  63. }
  64. type readButCopy struct {
  65. src io.Reader
  66. dst io.Writer
  67. }
  68. func (r *readButCopy) Read(p []byte) (int, error) {
  69. n, err := r.src.Read(p)
  70. if n > 0 {
  71. r.dst.Write(p[:n])
  72. }
  73. return n, err
  74. }