curl.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2015 The etcd Authors
  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 client
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "os"
  21. )
  22. var (
  23. cURLDebug = false
  24. )
  25. func EnablecURLDebug() {
  26. cURLDebug = true
  27. }
  28. func DisablecURLDebug() {
  29. cURLDebug = false
  30. }
  31. // printcURL prints the cURL equivalent request to stderr.
  32. // It returns an error if the body of the request cannot
  33. // be read.
  34. // The caller MUST cancel the request if there is an error.
  35. func printcURL(req *http.Request) error {
  36. if !cURLDebug {
  37. return nil
  38. }
  39. var (
  40. command string
  41. b []byte
  42. err error
  43. )
  44. if req.URL != nil {
  45. command = fmt.Sprintf("curl -X %s %s", req.Method, req.URL.String())
  46. }
  47. if req.Body != nil {
  48. b, err = ioutil.ReadAll(req.Body)
  49. if err != nil {
  50. return err
  51. }
  52. command += fmt.Sprintf(" -d %q", string(b))
  53. }
  54. fmt.Fprintf(os.Stderr, "cURL Command: %s\n", command)
  55. // reset body
  56. body := bytes.NewBuffer(b)
  57. req.Body = ioutil.NopCloser(body)
  58. return nil
  59. }