request.go 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * Copyright (c) 2022 Yansen Zhang
  3. * wxcomponent is licensed under Mulan PSL v2.
  4. * You can use this software according to the terms and conditions of the Mulan PSL v2.
  5. * You may obtain a copy of Mulan PSL v2 at:
  6. * http://license.coscl.org.cn/MulanPSL2
  7. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
  8. * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
  9. * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  10. * See the Mulan PSL v2 for more details.
  11. **/
  12. package request
  13. import (
  14. "bytes"
  15. "encoding/json"
  16. "errors"
  17. "io"
  18. "net/http"
  19. "gitee.com/yansen_zh/wxcomponent/utils/log"
  20. )
  21. func post(url string, contentType string, body []byte) ([]byte, error) {
  22. logger := log.GetLogger()
  23. logger.Info("发送请求: ", url)
  24. if len(body) > 0 {
  25. logger.Info(body)
  26. }
  27. resp, e1 := http.Post(url, contentType, bytes.NewReader(body))
  28. if e1 != nil {
  29. return nil, e1
  30. }
  31. if resp.StatusCode > 299 {
  32. return nil, errors.New(resp.Status)
  33. }
  34. body, e2 := io.ReadAll(resp.Body)
  35. resp.Body.Close()
  36. if e2 != nil {
  37. return nil, e2
  38. }
  39. logger.Info("微信端返回: ", body)
  40. return body, nil
  41. }
  42. // PostJSON 使用 POST 方式发送 json 数据
  43. func PostJSON(url string, body interface{}) ([]byte, error) {
  44. data, e1 := json.Marshal(body)
  45. if e1 != nil {
  46. return nil, e1
  47. }
  48. return post(url, ContentTypeJSON, data)
  49. }