123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- package wechat
- import (
- "bytes"
- "encoding/json"
- "io/ioutil"
- "net/http"
- "time"
- "gitee.com/xuyiping_admin/pkg/logger/zaplog"
- "gitee.com/xuyiping_admin/pkg/xerr"
- "go.uber.org/zap"
- )
- type ClientService struct {
- AppID string
- Secret string
- authClient *http.Client
- }
- func NewClientService(appid, secret string) *ClientService {
- return &ClientService{
- AppID: appid,
- Secret: secret,
- authClient: &http.Client{
- Timeout: time.Duration(60) * time.Second,
- },
- }
- }
- func (c *ClientService) doRequest(req *http.Request) ([]byte, error) {
- resp, err := c.authClient.Do(req)
- if err != nil {
- zaplog.Error("ClientService", zap.Any("authClient.Do", err))
- return nil, xerr.WithStack(err)
- }
- b, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- zaplog.Error("ClientService", zap.Any("ioutil.ReadAll", err))
- return nil, xerr.WithStack(err)
- }
- if resp.StatusCode != http.StatusOK {
- if len(b) > 0 {
- return nil, xerr.Customf("err:%v,body:%s", err, string(b))
- } else {
- return nil, xerr.Customf("err:%v", err)
- }
- }
- return b, nil
- }
- func (c *ClientService) DoGet(url string) ([]byte, error) {
- req, err := http.NewRequest(http.MethodGet, url, nil)
- if err != nil {
- zaplog.Error("ClientService", zap.Any("DoGet", err))
- return nil, err
- }
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Content-Type", "application/json")
- return c.doRequest(req)
- }
- func (c *ClientService) DoPost(url string, body interface{}) ([]byte, error) {
- b, err := json.Marshal(body)
- if err != nil {
- zaplog.Error("ClientService", zap.Any("DoPost-Marshal", err))
- return nil, xerr.WithStack(err)
- }
- req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(b))
- if err != nil {
- zaplog.Error("ClientService", zap.Any("NewRequest", err))
- return nil, xerr.WithStack(err)
- }
- req.Header.Add("Accept", "application/json")
- req.Header.Add("Content-Type", "application/json")
- return c.doRequest(req)
- }
|