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