client.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package jpush
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "io/ioutil"
  7. "net/http"
  8. "time"
  9. "go-common/library/stat"
  10. "go-common/library/stat/prom"
  11. )
  12. const (
  13. _charset = "UTF-8"
  14. _contentTypeJSON = "application/json"
  15. _pushURL = "https://api.jpush.cn/v3/push"
  16. // _scheduleURL = "https://api.jpush.cn/v3/schedules"
  17. // _reportURL = "https://report.jpush.cn/v3/received"
  18. )
  19. // PushResponse .
  20. type PushResponse struct {
  21. SendNo interface{} `json:"sendno,omitempty"`
  22. MsgID interface{} `json:"msg_id,omitempty"`
  23. IllegalTokens []string `json:"illegal_rids,omitempty"`
  24. Retry bool // 是否需要重试请求
  25. Error struct {
  26. Code int `json:"code"`
  27. Message string `json:"message"`
  28. } `json:"error,omitempty"`
  29. }
  30. // Client jpush http client.
  31. type Client struct {
  32. Auth string
  33. Stats stat.Stat
  34. Timeout time.Duration
  35. }
  36. // NewClient new client.
  37. func NewClient(appKey, secret string, timeout time.Duration) *Client {
  38. auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(appKey+":"+secret))
  39. return &Client{
  40. Auth: auth,
  41. Stats: prom.HTTPClient,
  42. Timeout: timeout,
  43. }
  44. }
  45. // Push push notification.
  46. func (cli *Client) Push(payload *Payload) (res *PushResponse, err error) {
  47. res = new(PushResponse)
  48. if cli.Stats != nil {
  49. now := time.Now()
  50. defer func() {
  51. cli.Stats.Timing(_pushURL, int64(time.Since(now)/time.Millisecond))
  52. // log.Info("jpush stats timing: %v", int64(time.Since(now)/time.Millisecond))
  53. if err != nil {
  54. cli.Stats.Incr(_pushURL, "failed")
  55. }
  56. }()
  57. }
  58. bs, err := payload.ToBytes()
  59. if err != nil {
  60. return
  61. }
  62. req, _ := http.NewRequest("POST", _pushURL, bytes.NewBuffer(bs))
  63. req.Header.Add("Charset", _charset)
  64. req.Header.Add("Authorization", cli.Auth)
  65. req.Header.Add("Content-Type", _contentTypeJSON)
  66. client := &http.Client{Timeout: cli.Timeout}
  67. resp, err := client.Do(req)
  68. if err != nil {
  69. res.Retry = true
  70. return
  71. }
  72. defer resp.Body.Close()
  73. r, err := ioutil.ReadAll(resp.Body)
  74. if err != nil {
  75. return
  76. }
  77. if err = json.Unmarshal(r, &res); err != nil {
  78. return
  79. }
  80. if res.Error.Code == ErrRetry || res.Error.Code == ErrInternal {
  81. res.Retry = true
  82. }
  83. return
  84. }