http_request.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "io/ioutil"
  9. "net/http"
  10. "property-thirdparty/errors"
  11. "strings"
  12. "time"
  13. "git.getensh.com/common/gopkgs/logger"
  14. "go.uber.org/zap"
  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. return nil, err
  55. }
  56. defer resp.Body.Close()
  57. if resp.StatusCode != http.StatusOK {
  58. logger.Error("thirdpary",
  59. zap.String("call", "http request"),
  60. zap.String("url", h.Url),
  61. zap.String("error", fmt.Sprintf("http wrong status:%d", resp.StatusCode)))
  62. return nil, errors.VendorError
  63. }
  64. contents, err := ioutil.ReadAll(resp.Body)
  65. if err != nil {
  66. logger.Error("thirdpary",
  67. zap.String("call", "http request"),
  68. zap.String("url", h.Url),
  69. zap.String("error", err.Error()))
  70. return nil, errors.VendorError
  71. }
  72. return contents, nil
  73. }