nunuxkeeper.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 nunuxkeeper
  5. import (
  6. "fmt"
  7. "net/url"
  8. "path"
  9. "github.com/miniflux/miniflux/http/client"
  10. )
  11. // Document structure of a Nununx Keeper document
  12. type Document struct {
  13. Title string `json:"title,omitempty"`
  14. Origin string `json:"origin,omitempty"`
  15. Content string `json:"content,omitempty"`
  16. ContentType string `json:"contentType,omitempty"`
  17. }
  18. // Client represents an Nunux Keeper client.
  19. type Client struct {
  20. baseURL string
  21. apiKey string
  22. }
  23. // AddEntry sends an entry to Nunux Keeper.
  24. func (c *Client) AddEntry(link, title, content string) error {
  25. if c.baseURL == "" || c.apiKey == "" {
  26. return fmt.Errorf("nunux-keeper: missing credentials")
  27. }
  28. doc := &Document{
  29. Title: title,
  30. Origin: link,
  31. Content: content,
  32. ContentType: "text/html",
  33. }
  34. apiURL, err := getAPIEndpoint(c.baseURL, "/v2/documents")
  35. if err != nil {
  36. return err
  37. }
  38. clt := client.New(apiURL)
  39. clt.WithCredentials("api", c.apiKey)
  40. response, err := clt.PostJSON(doc)
  41. if err != nil {
  42. return fmt.Errorf("nunux-keeper: unable to send entry: %v", err)
  43. }
  44. if response.HasServerFailure() {
  45. return fmt.Errorf("nunux-keeper: unable to send entry, status=%d", response.StatusCode)
  46. }
  47. return nil
  48. }
  49. // NewClient returns a new Nunux Keeepr client.
  50. func NewClient(baseURL, apiKey string) *Client {
  51. return &Client{baseURL: baseURL, apiKey: apiKey}
  52. }
  53. func getAPIEndpoint(baseURL, pathURL string) (string, error) {
  54. u, err := url.Parse(baseURL)
  55. if err != nil {
  56. return "", fmt.Errorf("nunux-keeper: invalid API endpoint: %v", err)
  57. }
  58. u.Path = path.Join(u.Path, pathURL)
  59. return u.String(), nil
  60. }