linkding.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package linkding // import "miniflux.app/integration/linkding"
  5. import (
  6. "fmt"
  7. "net/url"
  8. "miniflux.app/http/client"
  9. )
  10. // Document structure of a Linkding document
  11. type Document struct {
  12. Url string `json:"url,omitempty"`
  13. Title string `json:"title,omitempty"`
  14. }
  15. // Client represents an Linkding client.
  16. type Client struct {
  17. baseURL string
  18. apiKey string
  19. }
  20. // NewClient returns a new Linkding client.
  21. func NewClient(baseURL, apiKey string) *Client {
  22. return &Client{baseURL: baseURL, apiKey: apiKey}
  23. }
  24. // AddEntry sends an entry to Linkding.
  25. func (c *Client) AddEntry(title, url string) error {
  26. if c.baseURL == "" || c.apiKey == "" {
  27. return fmt.Errorf("linkding: missing credentials")
  28. }
  29. doc := &Document{
  30. Url: url,
  31. Title: title,
  32. }
  33. apiURL, err := getAPIEndpoint(c.baseURL, "/api/bookmarks/")
  34. if err != nil {
  35. return err
  36. }
  37. clt := client.New(apiURL)
  38. clt.WithAuthorization("Token " + c.apiKey)
  39. response, err := clt.PostJSON(doc)
  40. if err != nil {
  41. return fmt.Errorf("linkding: unable to send entry: %v", err)
  42. }
  43. if response.HasServerFailure() {
  44. return fmt.Errorf("linkding: unable to send entry, status=%d", response.StatusCode)
  45. }
  46. return nil
  47. }
  48. func getAPIEndpoint(baseURL, pathURL string) (string, error) {
  49. u, err := url.Parse(baseURL)
  50. if err != nil {
  51. return "", fmt.Errorf("linkding: invalid API endpoint: %v", err)
  52. }
  53. relative, err := url.Parse(pathURL)
  54. if err != nil {
  55. return "", fmt.Errorf("linkding: invalid API endpoint: %v", err)
  56. }
  57. u = u.ResolveReference(relative)
  58. return u.String(), nil
  59. }