| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- package httpHelper
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "github.com/pkg/errors"
- )
- // HTTPClientHelper 提供了对HTTP API调用的基本封装
- type HTTPClientHelper struct {
- client *http.Client
- }
- // NewHTTPClientHelper 创建一个新的HTTPClientHelper实例,并使用默认的http.Client
- func NewHTTPClientHelper() *HTTPClientHelper {
- return &HTTPClientHelper{
- client: &http.Client{},
- }
- }
- // Get 发起一个GET请求并返回响应体
- func (h *HTTPClientHelper) Get(url string) ([]byte, error) {
- resp, err := h.client.Get(url)
- if err != nil {
- return nil, errors.Wrap(err, "发起GET请求时出错")
- }
- defer func(Body io.ReadCloser) {
- _ = Body.Close()
- }(resp.Body)
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, errors.Wrap(err, "读取响应体时出错")
- }
- if resp.StatusCode >= 400 {
- return nil, fmt.Errorf("收到非成功状态码: %d", resp.StatusCode)
- }
- return body, nil
- }
- // PostJSON 发起一个POST请求,发送JSON格式的数据,并返回响应体
- func (h *HTTPClientHelper) PostJSON(url string, payload interface{}) ([]byte, error) {
- jsonPayload, err := json.Marshal(payload)
- if err != nil {
- return nil, errors.Wrap(err, "序列化JSON数据时出错")
- }
- req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonPayload))
- if err != nil {
- return nil, errors.Wrap(err, "创建POST请求时出错")
- }
- req.Header.Set("Content-Type", "application/json")
- resp, err := h.client.Do(req)
- if err != nil {
- return nil, errors.Wrap(err, "执行POST请求时出错")
- }
- defer func(Body io.ReadCloser) {
- _ = Body.Close()
- }(resp.Body)
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, errors.Wrap(err, "读取POST响应体时出错")
- }
- if resp.StatusCode >= 400 {
- return nil, fmt.Errorf("收到非成功状态码: %d", resp.StatusCode)
- }
- return body, nil
- }
|