http_request.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package thirdparty
  4. import (
  5. "bytes"
  6. "crypto/tls"
  7. "fmt"
  8. "gd_vehicle/errors"
  9. "io/ioutil"
  10. "net/http"
  11. "strings"
  12. "time"
  13. "go.uber.org/zap"
  14. )
  15. type HttpRequestWithHeadCommon struct {
  16. Url string
  17. Method string
  18. Head map[string]string
  19. TimeOut time.Duration
  20. Query map[string]string
  21. Body []byte
  22. }
  23. func joinGetRequestArgsCommon(data map[string]string) string {
  24. var path string
  25. if data != nil {
  26. path += "?"
  27. for k, v := range data {
  28. path += k + "=" + v + "&"
  29. }
  30. path = strings.TrimRight(path, "&")
  31. return path
  32. }
  33. return path
  34. }
  35. func (h HttpRequestWithHeadCommon) Request() ([]byte, error) {
  36. if len(h.Query) > 0 {
  37. h.Url = h.Url + joinGetRequestArgsCommon(h.Query)
  38. }
  39. request, err := http.NewRequest(h.Method, h.Url, bytes.NewReader(h.Body))
  40. for k, v := range h.Head {
  41. request.Header.Add(k, v)
  42. }
  43. //跳过证书验证
  44. tr := &http.Transport{
  45. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  46. }
  47. client := http.Client{
  48. Transport: tr,
  49. Timeout: h.TimeOut,
  50. }
  51. resp, err := client.Do(request)
  52. if err != nil {
  53. l.Error("thirdpary",
  54. zap.String("call", "http request"),
  55. zap.String("url", h.Url),
  56. zap.String("error", err.Error()))
  57. return nil, errors.VendorError
  58. }
  59. defer resp.Body.Close()
  60. if resp.StatusCode != http.StatusOK {
  61. l.Error("thirdpary",
  62. zap.String("call", "http request"),
  63. zap.String("url", h.Url),
  64. zap.String("error", fmt.Sprintf("http wrong status:%d", resp.StatusCode)))
  65. return nil, errors.VendorError
  66. }
  67. contents, err := ioutil.ReadAll(resp.Body)
  68. if err != nil {
  69. l.Error("thirdpary",
  70. zap.String("call", "http request"),
  71. zap.String("url", h.Url),
  72. zap.String("error", err.Error()))
  73. return nil, errors.VendorError
  74. }
  75. return contents, nil
  76. }