cubox.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. // Cubox API documentation: https://help.cubox.cc/save/api/
  4. package cubox // import "miniflux.app/v2/internal/integration/cubox"
  5. import (
  6. "bytes"
  7. "context"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "net/http"
  12. "time"
  13. "miniflux.app/v2/internal/version"
  14. )
  15. const defaultClientTimeout = 10 * time.Second
  16. type Client struct {
  17. apiLink string
  18. }
  19. func NewClient(apiLink string) *Client {
  20. return &Client{apiLink: apiLink}
  21. }
  22. func (c *Client) SaveLink(entryURL string) error {
  23. if c.apiLink == "" {
  24. return errors.New("cubox: missing API link")
  25. }
  26. requestBody, err := json.Marshal(&card{
  27. Type: "url",
  28. Content: entryURL,
  29. })
  30. if err != nil {
  31. return fmt.Errorf("cubox: unable to encode request body: %w", err)
  32. }
  33. ctx, cancel := context.WithTimeout(context.Background(), defaultClientTimeout)
  34. defer cancel()
  35. request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.apiLink, bytes.NewReader(requestBody))
  36. if err != nil {
  37. return fmt.Errorf("cubox: unable to create request: %w", err)
  38. }
  39. request.Header.Set("Content-Type", "application/json")
  40. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  41. response, err := http.DefaultClient.Do(request)
  42. if err != nil {
  43. return fmt.Errorf("cubox: unable to send request: %w", err)
  44. }
  45. defer response.Body.Close()
  46. if response.StatusCode != 200 {
  47. return fmt.Errorf("cubox: unable to save link: status=%d", response.StatusCode)
  48. }
  49. return nil
  50. }
  51. type card struct {
  52. Type string `json:"type"`
  53. Content string `json:"content"`
  54. }