bullet.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. type Bullet struct {
  11. Token string
  12. }
  13. func (b Bullet) newRequest(body io.Reader) (*http.Request, error) {
  14. request, err := http.NewRequest(http.MethodPost, "https://api.pushbullet.com/v2/pushes", body)
  15. if err != nil {
  16. return nil, err
  17. }
  18. request.Header.Add("Access-Token", b.Token)
  19. request.Header.Add("Content-Type", "application/json")
  20. return request, nil
  21. }
  22. func (b Bullet) send(push Push) error {
  23. reader, errReader := push.GetReader()
  24. if errReader != nil {
  25. return errReader
  26. }
  27. request, errRequest := b.newRequest(reader)
  28. if errRequest != nil {
  29. return errRequest
  30. }
  31. client := http.Client{}
  32. response, errResponse := client.Do(request)
  33. if errResponse != nil {
  34. return errResponse
  35. }
  36. defer response.Body.Close()
  37. if response.StatusCode != http.StatusOK {
  38. var errBullet BulletError
  39. decoder := json.NewDecoder(response.Body)
  40. errJSON := decoder.Decode(&errBullet)
  41. if errJSON != nil {
  42. return errJSON
  43. }
  44. return errBullet.GetError()
  45. }
  46. return nil
  47. }
  48. //Send push note with given title and text
  49. func (b Bullet) SendNote(title, text string) error {
  50. note := NewNotePush(title, text)
  51. err := b.send(note)
  52. return err
  53. }
  54. //Send push link with given title, text and link
  55. func (b Bullet) SendLink(title, text, link string) error {
  56. linkPush := NewLinkPush(title, text, link)
  57. err := b.send(linkPush)
  58. return err
  59. }