12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package backend
- 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 FeedingService struct {
- authClient *http.Client
- }
- func NewFeedingService() *FeedingService {
- return &FeedingService{
- authClient: &http.Client{
- Timeout: time.Duration(60) * time.Second,
- },
- }
- }
- func (c *FeedingService) doRequest(req *http.Request) ([]byte, error) {
- resp, err := http.DefaultClient.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 *FeedingService) 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 *FeedingService) 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)
- }
|