bullet.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. //Send push note with given title and text
  23. func (b Bullet) SendNote(title, text string) error {
  24. note := NewNotePush(title, text)
  25. reader, errReader := note.GetReader()
  26. if errReader != nil {
  27. return errReader
  28. }
  29. request, errRequest := b.newRequest(reader)
  30. if errRequest != nil {
  31. return errRequest
  32. }
  33. client := http.Client{}
  34. response, errResponse := client.Do(request)
  35. if errResponse != nil {
  36. return errResponse
  37. }
  38. defer response.Body.Close()
  39. if response.StatusCode != http.StatusOK {
  40. var errBullet BulletError
  41. decoder := json.NewDecoder(response.Body)
  42. errJSON := decoder.Decode(&errBullet)
  43. if errJSON != nil {
  44. return errJSON
  45. }
  46. return errBullet.GetError()
  47. }
  48. return nil
  49. }