88 "encoding/json"
99 "errors"
1010 "fmt"
11+ "io"
1112 "net/http"
1213 "time"
1314
@@ -18,12 +19,23 @@ import (
1819const defaultClientTimeout = 10 * time .Second
1920
2021type Client struct {
21- baseURL string
22- apiKey string
22+ baseURL string
23+ apiKey string
24+ collectionId * int64
2325}
2426
25- func NewClient (baseURL , apiKey string ) * Client {
26- return & Client {baseURL : baseURL , apiKey : apiKey }
27+ type linkwardenCollection struct {
28+ Id * int64 `json:"id"`
29+ }
30+
31+ type linkwardenRequest struct {
32+ URL string `json:"url"`
33+ Name string `json:"name"`
34+ Collection linkwardenCollection `json:"collection,omitempty"`
35+ }
36+
37+ func NewClient (baseURL , apiKey string , collectionId * int64 ) * Client {
38+ return & Client {baseURL : baseURL , apiKey : apiKey , collectionId : collectionId }
2739}
2840
2941func (c * Client ) CreateBookmark (entryURL , entryTitle string ) error {
@@ -36,10 +48,16 @@ func (c *Client) CreateBookmark(entryURL, entryTitle string) error {
3648 return fmt .Errorf (`linkwarden: invalid API endpoint: %v` , err )
3749 }
3850
39- requestBody , err := json .Marshal (map [string ]string {
40- "url" : entryURL ,
41- "name" : entryTitle ,
42- })
51+ payload := linkwardenRequest {
52+ URL : entryURL ,
53+ Name : entryTitle ,
54+ }
55+
56+ if c .collectionId != nil {
57+ payload .Collection = linkwardenCollection {Id : c .collectionId }
58+ }
59+
60+ requestBody , err := json .Marshal (payload )
4361
4462 if err != nil {
4563 return fmt .Errorf ("linkwarden: unable to encode request body: %v" , err )
@@ -61,8 +79,13 @@ func (c *Client) CreateBookmark(entryURL, entryTitle string) error {
6179 }
6280 defer response .Body .Close ()
6381
82+ responseBody , err := io .ReadAll (response .Body )
83+ if err != nil {
84+ return fmt .Errorf ("linkwarden: unable to read response body: %v" , err )
85+ }
86+
6487 if response .StatusCode >= 400 {
65- return fmt .Errorf ("linkwarden: unable to create link: url=%s status=%d " , apiEndpoint , response .StatusCode )
88+ return fmt .Errorf ("linkwarden: unable to create link: status=%d body=%s " , response .StatusCode , string ( responseBody ) )
6689 }
6790
6891 return nil
0 commit comments