HTTPClientHelper.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package httpHelper
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "github.com/pkg/errors"
  9. )
  10. // HTTPClientHelper 提供了对HTTP API调用的基本封装
  11. type HTTPClientHelper struct {
  12. client *http.Client
  13. }
  14. // NewHTTPClientHelper 创建一个新的HTTPClientHelper实例,并使用默认的http.Client
  15. func NewHTTPClientHelper() *HTTPClientHelper {
  16. return &HTTPClientHelper{
  17. client: &http.Client{},
  18. }
  19. }
  20. // Get 发起一个GET请求并返回响应体
  21. func (h *HTTPClientHelper) Get(url string) ([]byte, error) {
  22. resp, err := h.client.Get(url)
  23. if err != nil {
  24. return nil, errors.Wrap(err, "发起GET请求时出错")
  25. }
  26. defer func(Body io.ReadCloser) {
  27. _ = Body.Close()
  28. }(resp.Body)
  29. body, err := io.ReadAll(resp.Body)
  30. if err != nil {
  31. return nil, errors.Wrap(err, "读取响应体时出错")
  32. }
  33. if resp.StatusCode >= 400 {
  34. return nil, fmt.Errorf("收到非成功状态码: %d", resp.StatusCode)
  35. }
  36. return body, nil
  37. }
  38. // PostJSON 发起一个POST请求,发送JSON格式的数据,并返回响应体
  39. func (h *HTTPClientHelper) PostJSON(url string, payload interface{}) ([]byte, error) {
  40. jsonPayload, err := json.Marshal(payload)
  41. if err != nil {
  42. return nil, errors.Wrap(err, "序列化JSON数据时出错")
  43. }
  44. req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonPayload))
  45. if err != nil {
  46. return nil, errors.Wrap(err, "创建POST请求时出错")
  47. }
  48. req.Header.Set("Content-Type", "application/json")
  49. resp, err := h.client.Do(req)
  50. if err != nil {
  51. return nil, errors.Wrap(err, "执行POST请求时出错")
  52. }
  53. defer func(Body io.ReadCloser) {
  54. _ = Body.Close()
  55. }(resp.Body)
  56. body, err := io.ReadAll(resp.Body)
  57. if err != nil {
  58. return nil, errors.Wrap(err, "读取POST响应体时出错")
  59. }
  60. if resp.StatusCode >= 400 {
  61. return nil, fmt.Errorf("收到非成功状态码: %d", resp.StatusCode)
  62. }
  63. return body, nil
  64. }