http.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. /*Transport: &http.Transport{
  23. MaxIdleConnsPerHost: 50,
  24. },*/
  25. Timeout: time.Duration(5) * time.Second,
  26. },
  27. }
  28. }
  29. func (c *ClientService) doRequest(req *http.Request) ([]byte, error) {
  30. resp, err := c.authClient.Do(req)
  31. if err != nil {
  32. zaplog.Error("ClientService", zap.Any("authClient.Do", err))
  33. return nil, xerr.WithStack(err)
  34. }
  35. b, err := ioutil.ReadAll(resp.Body)
  36. if err != nil {
  37. zaplog.Error("ClientService", zap.Any("ioutil.ReadAll", err))
  38. return nil, xerr.WithStack(err)
  39. }
  40. if resp.StatusCode != http.StatusOK {
  41. if len(b) > 0 {
  42. return nil, xerr.Customf("err:%v,body:%s", err, string(b))
  43. } else {
  44. return nil, xerr.Customf("err:%v", err)
  45. }
  46. }
  47. return b, nil
  48. }
  49. func (c *ClientService) DoGet(url string) ([]byte, error) {
  50. req, err := http.NewRequest(http.MethodGet, url, nil)
  51. if err != nil {
  52. zaplog.Error("ClientService", zap.Any("DoGet", err))
  53. return nil, err
  54. }
  55. req.Header.Add("Accept", "application/json")
  56. req.Header.Add("Content-Type", "application/json")
  57. return c.doRequest(req)
  58. }
  59. func (c *ClientService) DoPost(url string, body interface{}) ([]byte, error) {
  60. b, err := json.Marshal(body)
  61. if err != nil {
  62. zaplog.Error("ClientService", zap.Any("DoPost-Marshal", err))
  63. return nil, xerr.WithStack(err)
  64. }
  65. req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(b))
  66. if err != nil {
  67. zaplog.Error("ClientService", zap.Any("NewRequest", err))
  68. return nil, xerr.WithStack(err)
  69. }
  70. req.Header.Add("Accept", "application/json")
  71. req.Header.Add("Content-Type", "application/json")
  72. return c.doRequest(req)
  73. }