http_request.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package utils
  4. import (
  5. "bytes"
  6. "crypto/tls"
  7. "fmt"
  8. "gd_auth_check/errors"
  9. "go.uber.org/zap"
  10. "io/ioutil"
  11. "net/http"
  12. "strings"
  13. "time"
  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. }