request.go 859B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package request
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "gitee.com/yansen_zh/wxcomponent/utils/log"
  9. )
  10. func post(url string, contentType string, body []byte) ([]byte, error) {
  11. logger := log.GetLogger()
  12. logger.Info("发送请求: ", url)
  13. if len(body) > 0 {
  14. logger.Info(body)
  15. }
  16. resp, e1 := http.Post(url, contentType, bytes.NewReader(body))
  17. if e1 != nil {
  18. return nil, e1
  19. }
  20. if resp.StatusCode > 299 {
  21. return nil, errors.New(resp.Status)
  22. }
  23. body, e2 := io.ReadAll(resp.Body)
  24. resp.Body.Close()
  25. if e2 != nil {
  26. return nil, e2
  27. }
  28. logger.Info("微信端返回: ", body)
  29. return body, nil
  30. }
  31. // PostJSON 使用 POST 方式发送 json 数据
  32. func PostJSON(url string, body interface{}) ([]byte, error) {
  33. data, e1 := json.Marshal(body)
  34. if e1 != nil {
  35. return nil, e1
  36. }
  37. return post(url, ContentTypeJSON, data)
  38. }