蛋蛋星球-制度模式
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.4 KiB

  1. package jpush
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "runtime"
  9. )
  10. type Client struct {
  11. AppKey string
  12. MasterSecret string
  13. pushUrl string
  14. reportUrl string
  15. deviceUrl string
  16. }
  17. func NewClient(appKey, masterSecret string) *Client {
  18. client := &Client{AppKey: appKey, MasterSecret: masterSecret}
  19. client.pushUrl = "https://api.jpush.cn"
  20. client.reportUrl = "https://report.jpush.cn"
  21. client.deviceUrl = "https://device.jpush.cn"
  22. return client
  23. }
  24. func (c *Client) getAuthorization(isGroup bool) string {
  25. str := c.AppKey + ":" + c.MasterSecret
  26. if isGroup {
  27. str = "group-" + str
  28. }
  29. buf := []byte(str)
  30. return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString(buf))
  31. }
  32. func (c *Client) getUserAgent() string {
  33. return fmt.Sprintf("(%s) go/%s", runtime.GOOS, runtime.Version())
  34. }
  35. func (c *Client) request(method, link string, body io.Reader, isGroup bool) (*Response, error) {
  36. req, err := http.NewRequest(method, link, body)
  37. if err != nil {
  38. return nil, err
  39. }
  40. req.Header.Set("Authorization", c.getAuthorization(isGroup))
  41. req.Header.Set("User-Agent", c.getUserAgent())
  42. req.Header.Set("Content-Type", "application/json")
  43. client := &http.Client{}
  44. resp, err := client.Do(req)
  45. if err != nil {
  46. return nil, err
  47. }
  48. defer resp.Body.Close()
  49. buf, err := ioutil.ReadAll(resp.Body)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return &Response{data: buf}, nil
  54. }