request.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. "net/url"
  20. wxerr "gitee.com/yansen_zh/wxcomponent/errors"
  21. "gitee.com/yansen_zh/wxcomponent/utils/log"
  22. )
  23. func post(url string, contentType string, body []byte) ([]byte, error) {
  24. logger := log.GetLogger()
  25. logger.Info("发送请求: ", url)
  26. if len(body) > 0 {
  27. logger.Info(body)
  28. }
  29. resp, e1 := http.Post(url, contentType, bytes.NewReader(body))
  30. if e1 != nil {
  31. return nil, e1
  32. }
  33. if resp.StatusCode > 299 {
  34. return nil, errors.New(resp.Status)
  35. }
  36. body, e2 := io.ReadAll(resp.Body)
  37. resp.Body.Close()
  38. if e2 != nil {
  39. return nil, e2
  40. }
  41. logger.Info("微信端返回: ", body)
  42. return body, nil
  43. }
  44. // PostJSON 使用 POST 方式发送 json 数据
  45. func PostJSON(addr string, query *url.Values, body interface{}) ([]byte, error) {
  46. apiURL, e0 := ParseURL(addr, query)
  47. if e0 != nil {
  48. return nil, e0
  49. }
  50. data, e1 := json.Marshal(body)
  51. if e1 != nil {
  52. return nil, e1
  53. }
  54. resp, e2 := post(apiURL.String(), ContentTypeJSON, data)
  55. if e2 != nil {
  56. return nil, e2
  57. }
  58. e3 := wxerr.Error{}
  59. if err := json.Unmarshal(resp, &e3); err != nil {
  60. return nil, err
  61. }
  62. if e3.Code != 0 {
  63. return nil, e3
  64. }
  65. return resp, nil
  66. }