miniflux/internal/integration/pocket/pocket.go

71 lines
1.8 KiB
Go
Raw Normal View History

// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
2018-05-20 22:31:56 +02:00
package pocket // import "miniflux.app/v2/internal/integration/pocket"
2018-05-20 22:31:56 +02:00
import (
"bytes"
"encoding/json"
2018-05-20 22:31:56 +02:00
"fmt"
"net/http"
"time"
2018-05-20 22:31:56 +02:00
"miniflux.app/v2/internal/version"
2018-05-20 22:31:56 +02:00
)
const defaultClientTimeout = 10 * time.Second
2018-05-20 22:31:56 +02:00
type Client struct {
consumerKey string
accessToken string
2018-05-20 22:31:56 +02:00
}
func NewClient(consumerKey, accessToken string) *Client {
return &Client{consumerKey, accessToken}
}
func (c *Client) AddURL(entryURL, entryTitle string) error {
2018-05-20 22:31:56 +02:00
if c.consumerKey == "" || c.accessToken == "" {
return fmt.Errorf("pocket: missing consumer key or access token")
}
apiEndpoint := "https://getpocket.com/v3/add"
requestBody, err := json.Marshal(&createItemRequest{
2018-05-20 22:31:56 +02:00
AccessToken: c.accessToken,
ConsumerKey: c.consumerKey,
Title: entryTitle,
URL: entryURL,
})
if err != nil {
return fmt.Errorf("pocket: unable to encode request body: %v", err)
}
request, err := http.NewRequest(http.MethodPost, apiEndpoint, bytes.NewReader(requestBody))
if err != nil {
return fmt.Errorf("pocket: unable to create request: %v", err)
2018-05-20 22:31:56 +02:00
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("User-Agent", "Miniflux/"+version.Version)
httpClient := &http.Client{Timeout: defaultClientTimeout}
response, err := httpClient.Do(request)
if err != nil {
return fmt.Errorf("pocket: unable to send request: %v", err)
}
defer response.Body.Close()
if response.StatusCode >= 400 {
return fmt.Errorf("pocket: unable to create item: url=%s status=%d", apiEndpoint, response.StatusCode)
2018-05-20 22:31:56 +02:00
}
return nil
2018-05-20 22:31:56 +02:00
}
type createItemRequest struct {
AccessToken string `json:"access_token"`
ConsumerKey string `json:"consumer_key"`
Title string `json:"title,omitempty"`
URL string `json:"url"`
}