-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
77 lines (67 loc) · 1.94 KB
/
client.go
File metadata and controls
77 lines (67 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package goodreads
import (
"errors"
"net/http"
"github.com/mrjones/oauth"
)
const (
REQUEST_TOKEN_URL = "https://www.goodreads.com/oauth/request_token"
AUTHORIZE_TOKEN_URL = "https://www.goodreads.com/oauth/authorize"
ACCESS_TOKEN_URL = "https://www.goodreads.com/oauth/access_token"
)
//Client is the Goodreads API Client object
type Client struct {
Consumer *oauth.Consumer
user *oauth.AccessToken
client *http.Client
consumerKey string
}
//NewClient is the constructor with only the Consumer key and secret
func NewClient(key string, secret string) *Client {
c := Client{
consumerKey: key,
}
c.SetConsumer(key, secret)
return &c
}
// Constructor with Consumer key/secret and user token/secret
func NewClientWithToken(consumerKey, consumerSecret, token, tokenSecret string) *Client {
c := NewClient(consumerKey, consumerSecret)
c.SetToken(token, tokenSecret)
return c
}
// Set Consumer credentials, invalidates any previously cached client
func (c *Client) SetConsumer(consumerKey string, consumerSecret string) {
c.Consumer = oauth.NewConsumer(consumerKey, consumerSecret,
oauth.ServiceProvider{
RequestTokenUrl: REQUEST_TOKEN_URL,
AuthorizeTokenUrl: AUTHORIZE_TOKEN_URL,
AccessTokenUrl: ACCESS_TOKEN_URL,
})
c.client = nil
}
// Set user credentials, invalidates any previously cached client
func (c *Client) SetToken(token string, secret string) {
c.user = &oauth.AccessToken{
AdditionalData: nil,
Secret: secret,
Token: token,
}
c.client = nil
}
// Retrieve the underlying HTTP client
func (c *Client) GetHttpClient() (*http.Client, error) {
if c.Consumer == nil {
return nil, errors.New("Consumer credentials are not set")
}
if c.user == nil {
c.SetToken("", "")
}
if c.client == nil {
c.client, _ = c.Consumer.MakeHttpClient(c.user)
c.client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
}
return c.client, nil
}