123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- /**
- * Copyright (c) 2022 Yansen Zhang
- * wxcomponent is licensed under Mulan PSL v2.
- * You can use this software according to the terms and conditions of the Mulan PSL v2.
- * You may obtain a copy of Mulan PSL v2 at:
- * http://license.coscl.org.cn/MulanPSL2
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
- * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
- * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
- * See the Mulan PSL v2 for more details.
- **/
-
- package request
-
- import (
- "bytes"
- "encoding/json"
- "errors"
- "io"
- "net/http"
- "net/url"
-
- wxerr "gitee.com/yansen_zh/wxcomponent/errors"
- "gitee.com/yansen_zh/wxcomponent/utils/log"
- )
-
- func Fetch(method, url string, contentType string, body []byte) ([]byte, error) {
-
- logger := log.GetLogger()
- logger.Info("发送请求: [", method, "] ", url)
-
- if len(body) > 0 {
- logger.Info(body)
- }
-
- var resp *http.Response
- var err error
-
- if method == "POST" {
- resp, err = http.Post(url, contentType, bytes.NewReader(body))
- } else {
- resp, err = http.Get(url)
- }
-
- if err != nil {
- return nil, err
- }
-
- if resp.StatusCode > 299 {
- return nil, errors.New(resp.Status)
- }
-
- body, e2 := io.ReadAll(resp.Body)
- resp.Body.Close()
- if e2 != nil {
- return nil, e2
- }
-
- logger.Info("微信端返回: ", body)
-
- return body, nil
- }
-
- // PostJSON 使用 POST 方式发送 json 数据
- func PostJSON(addr string, query *url.Values, body interface{}) ([]byte, error) {
- apiURL, e0 := ParseURL(addr, query)
- if e0 != nil {
- return nil, e0
- }
-
- data, e1 := json.Marshal(body)
- if e1 != nil {
- return nil, e1
- }
-
- resp, e2 := Fetch("POST", apiURL.String(), ContentTypeJSON, data)
- if e2 != nil {
- return nil, e2
- }
-
- e3 := wxerr.Error{}
- if err := json.Unmarshal(resp, &e3); err != nil {
- return nil, err
- }
-
- if e3.Code != 0 {
- return nil, &e3
- }
-
- return resp, nil
- }
-
- func GetJSON(addr string, query *url.Values) ([]byte, error) {
- apiURL, e0 := ParseURL(addr, query)
- if e0 != nil {
- return nil, e0
- }
-
- resp, e2 := Fetch("GET", apiURL.String(), "", nil)
- if e2 != nil {
- return nil, e2
- }
-
- e3 := wxerr.Error{}
- if err := json.Unmarshal(resp, &e3); err != nil {
- return nil, err
- }
-
- if e3.Code != 0 {
- return nil, e3
- }
-
- return resp, nil
- }
|