client.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package ifttt
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/url"
  8. goahttp "goa.design/goa/v3/http"
  9. )
  10. type (
  11. Client interface {
  12. Trigger(ctx context.Context, present bool) (event string, err error)
  13. }
  14. client struct {
  15. c *http.Client
  16. presentEvent, absentEvent string
  17. presentURL, absentURL *url.URL
  18. debug bool
  19. }
  20. )
  21. func NewClient(c *http.Client, baseURL, key, presentEvent, absentEvent string, debug bool) (Client, error) {
  22. u, err := url.Parse(baseURL)
  23. if err != nil {
  24. return nil, err
  25. }
  26. presentURL, absentURL := *u, *u
  27. presentURL.Path = "/trigger/" + presentEvent + "/with/key/" + key
  28. absentURL.Path = "/trigger/" + absentEvent + "/with/key/" + key
  29. return &client{
  30. c: c,
  31. presentEvent: presentEvent,
  32. absentEvent: absentEvent,
  33. presentURL: &presentURL,
  34. absentURL: &absentURL,
  35. debug: debug,
  36. }, nil
  37. }
  38. func (c *client) Trigger(ctx context.Context, present bool) (event string, err error) {
  39. var u *url.URL
  40. if present {
  41. event = c.presentEvent
  42. u = c.presentURL
  43. } else {
  44. event = c.absentEvent
  45. u = c.absentURL
  46. }
  47. req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), nil)
  48. if err != nil {
  49. return
  50. }
  51. doer := goahttp.Doer(c.c)
  52. if c.debug {
  53. doer = goahttp.NewDebugDoer(doer)
  54. }
  55. resp, err := doer.Do(req)
  56. if err != nil {
  57. return
  58. }
  59. defer resp.Body.Close()
  60. if resp.StatusCode != http.StatusOK {
  61. var b []byte
  62. b, err = io.ReadAll(resp.Body)
  63. if err != nil {
  64. err = fmt.Errorf("%v: <failed to read body: %w>", resp.Status, err)
  65. return
  66. } else if len(b) == 0 {
  67. b = []byte("<empty body>")
  68. }
  69. err = fmt.Errorf("%v: %s", resp.Status, b)
  70. return
  71. }
  72. return
  73. }