bullet.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package bullet
  2. import (
  3. "encoding/json"
  4. "io"
  5. "net/http"
  6. )
  7. const (
  8. shortTimeFormat = "2006-01-02 15:04"
  9. )
  10. //Bullet client for the Pushbullet API
  11. type Bullet struct {
  12. token string
  13. }
  14. //NewBullet creates new Bullet using provided token
  15. func NewBullet(token string) Bullet {
  16. b := Bullet{token: token}
  17. return b
  18. }
  19. func (b Bullet) newRequest(body io.Reader) (*http.Request, error) {
  20. request, err := http.NewRequest(http.MethodPost, "https://api.pushbullet.com/v2/pushes", body)
  21. if err != nil {
  22. return nil, err
  23. }
  24. request.Header.Add("Access-Token", b.token)
  25. request.Header.Add("Content-Type", "application/json")
  26. return request, nil
  27. }
  28. func (b Bullet) send(push Push) error {
  29. reader, errReader := push.GetReader()
  30. if errReader != nil {
  31. return errReader
  32. }
  33. request, errRequest := b.newRequest(reader)
  34. if errRequest != nil {
  35. return errRequest
  36. }
  37. client := http.Client{}
  38. response, errResponse := client.Do(request)
  39. if errResponse != nil {
  40. return errResponse
  41. }
  42. defer response.Body.Close()
  43. if response.StatusCode != http.StatusOK {
  44. var errBullet BulletError
  45. decoder := json.NewDecoder(response.Body)
  46. errJSON := decoder.Decode(&errBullet)
  47. if errJSON != nil {
  48. return errJSON
  49. }
  50. return errBullet.GetError()
  51. }
  52. return nil
  53. }
  54. //SendNote sends push note with given title and text
  55. func (b Bullet) SendNote(title, text string) error {
  56. note := NewNotePush(title, text)
  57. err := b.send(note)
  58. return err
  59. }
  60. //SendLink sends push link with given title, text and link
  61. func (b Bullet) SendLink(title, text, link string) error {
  62. linkPush := NewLinkPush(title, text, link)
  63. err := b.send(linkPush)
  64. return err
  65. }