4
0

webhook.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package webhook // import "miniflux.app/v2/internal/integration/webhook"
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "time"
  10. "miniflux.app/v2/internal/crypto"
  11. "miniflux.app/v2/internal/model"
  12. "miniflux.app/v2/internal/version"
  13. )
  14. const defaultClientTimeout = 10 * time.Second
  15. type Client struct {
  16. webhookURL string
  17. webhookSecret string
  18. }
  19. func NewClient(webhookURL, webhookSecret string) *Client {
  20. return &Client{webhookURL, webhookSecret}
  21. }
  22. func (c *Client) SendWebhook(entries model.Entries) error {
  23. if c.webhookURL == "" {
  24. return fmt.Errorf(`webhook: missing webhook URL`)
  25. }
  26. if len(entries) == 0 {
  27. return nil
  28. }
  29. requestBody, err := json.Marshal(entries)
  30. if err != nil {
  31. return fmt.Errorf("webhook: unable to encode request body: %v", err)
  32. }
  33. request, err := http.NewRequest(http.MethodPost, c.webhookURL, bytes.NewReader(requestBody))
  34. if err != nil {
  35. return fmt.Errorf("webhook: unable to create request: %v", err)
  36. }
  37. request.Header.Set("Content-Type", "application/json")
  38. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  39. request.Header.Set("X-Miniflux-Signature", crypto.GenerateSHA256Hmac(c.webhookSecret, requestBody))
  40. httpClient := &http.Client{Timeout: defaultClientTimeout}
  41. response, err := httpClient.Do(request)
  42. if err != nil {
  43. return fmt.Errorf("webhook: unable to send request: %v", err)
  44. }
  45. defer response.Body.Close()
  46. if response.StatusCode >= 400 {
  47. return fmt.Errorf("webhook: incorrect response status code: url=%s status=%d", c.webhookURL, response.StatusCode)
  48. }
  49. return nil
  50. }