client.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package jpush
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "io/ioutil"
  6. "net/http"
  7. "time"
  8. "go-common/library/stat"
  9. "go-common/library/stat/prom"
  10. )
  11. const (
  12. pushURL = "https://api.jpush.cn/v3/push"
  13. // 如果创建的极光应用分配的北京机房,并且 API 调用方的服务器也位于北京,则比较适合调用极光北京机房的 API,可以提升一定的响应速度。
  14. // PUSH_URL = "https://bjapi.push.jiguang.cn/v3/push"
  15. // VALIDATE_URL = "https://api.jpush.cn/v3/push/validate"
  16. // GROUP_PUSH_URL = "https://api.jpush.cn/v3/grouppush"
  17. )
  18. // Client for JPush
  19. type Client struct {
  20. Auth string
  21. Stats stat.Stat
  22. Timeout time.Duration
  23. }
  24. // New .
  25. func New(appKey string, secretKey string, timeout time.Duration) *Client {
  26. auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(appKey+":"+secretKey))
  27. return &Client{
  28. Auth: auth,
  29. Stats: prom.HTTPClient,
  30. Timeout: timeout,
  31. }
  32. }
  33. // Push .
  34. func (clt *Client) Push(b []byte) (resp []byte, err error) {
  35. if clt.Stats != nil {
  36. now := time.Now()
  37. defer func() {
  38. clt.Stats.Timing(pushURL, int64(time.Since(now)/time.Millisecond))
  39. // log.Info("jpush stats timing: %v", int64(time.Since(now)/time.Millisecond))
  40. if err != nil {
  41. clt.Stats.Incr(pushURL, "failed")
  42. }
  43. }()
  44. }
  45. req, err := http.NewRequest("POST", pushURL, bytes.NewBuffer(b))
  46. req.Header.Add("Charset", "UTF-8")
  47. req.Header.Add("Authorization", clt.Auth)
  48. req.Header.Add("Content-Type", "application/json")
  49. client := &http.Client{Timeout: clt.Timeout}
  50. httpResp, err := client.Do(req)
  51. if err != nil {
  52. return
  53. }
  54. defer httpResp.Body.Close()
  55. return ioutil.ReadAll(httpResp.Body)
  56. }
  57. // GetTimeout .
  58. func (clt *Client) GetTimeout() time.Duration {
  59. return clt.Timeout
  60. }