feeding.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package backend
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io/ioutil"
  6. "net/http"
  7. "time"
  8. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  9. "gitee.com/xuyiping_admin/pkg/xerr"
  10. "go.uber.org/zap"
  11. )
  12. type FeedingService struct {
  13. authClient *http.Client
  14. }
  15. func NewFeedingService() *FeedingService {
  16. return &FeedingService{
  17. authClient: &http.Client{
  18. Timeout: time.Duration(60) * time.Second,
  19. },
  20. }
  21. }
  22. func (c *FeedingService) doRequest(req *http.Request) ([]byte, error) {
  23. resp, err := http.DefaultClient.Do(req)
  24. if err != nil {
  25. zaplog.Error("ClientService", zap.Any("authClient.Do", err))
  26. return nil, xerr.WithStack(err)
  27. }
  28. b, err := ioutil.ReadAll(resp.Body)
  29. if err != nil {
  30. zaplog.Error("ClientService", zap.Any("ioutil.ReadAll", err))
  31. return nil, xerr.WithStack(err)
  32. }
  33. if resp.StatusCode != http.StatusOK {
  34. if len(b) > 0 {
  35. return nil, xerr.Customf("err:%v,body:%s", err, string(b))
  36. } else {
  37. return nil, xerr.Customf("err:%v", err)
  38. }
  39. }
  40. return b, nil
  41. }
  42. func (c *FeedingService) DoGet(url string) ([]byte, error) {
  43. req, err := http.NewRequest(http.MethodGet, url, nil)
  44. if err != nil {
  45. zaplog.Error("ClientService", zap.Any("DoGet", err))
  46. return nil, err
  47. }
  48. req.Header.Add("Accept", "application/json")
  49. req.Header.Add("Content-Type", "application/json")
  50. return c.doRequest(req)
  51. }
  52. func (c *FeedingService) DoPost(url string, body interface{}) ([]byte, error) {
  53. b, err := json.Marshal(body)
  54. if err != nil {
  55. zaplog.Error("ClientService", zap.Any("DoPost-Marshal", err))
  56. return nil, xerr.WithStack(err)
  57. }
  58. req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(b))
  59. if err != nil {
  60. zaplog.Error("ClientService", zap.Any("NewRequest", err))
  61. return nil, xerr.WithStack(err)
  62. }
  63. req.Header.Add("Accept", "application/json")
  64. req.Header.Add("Content-Type", "application/json")
  65. return c.doRequest(req)
  66. }