http.go 1.9 KB

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