1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- package wechat
- import (
- "bytes"
- "encoding/json"
- "io/ioutil"
- "kpt-tmr-group/pkg/logger/zaplog"
- "kpt-tmr-group/pkg/xerr"
- "net/http"
- "time"
- "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(5) * 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)
- }
|