forked from azer/go-flickr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
80 lines (65 loc) · 2.09 KB
/
client.go
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
78
79
80
package flickr
import (
"fmt"
"io/ioutil"
"net/http"
)
type Params map[string]string
type Client struct {
Key string
Token string
Sig string
URL string
}
// ApiKeyEnvVar is the name of the environment variable that is search for the Flickr API Key
const ApiKeyEnvVar = "FLICKR_API_KEY"
const flickrURL = "https://api.flickr.com/services/rest"
// NewClient creates a client that can access the Flickr API,
// attempting fo fetch the API Key from the file ./.env
func NewClient() (*Client, error) {
return NewClientEnvFile("")
}
// NewClientApiKey creates a client that can access the Flickr API using the supplied API Key
func NewClientApiKey(apiKey string) *Client {
return &Client{Key: apiKey, URL: flickrURL}
}
// NewClientEnvFile creates a client that can access the Flickr API,
// attempting fo fetch the API Key first from an environment file specified in envFileName
// then from the file ./.env
func NewClientEnvFile(envFileName string) (*Client, error) {
key, err := getApiKey("", envFileName)
if err != nil {
return nil, err
}
return &Client{Key: key, URL: flickrURL}, nil
}
// NewClientEnvFile creates a client that can access the Flickr API,
// by searching for an environment variable named by ApiKeyEnvVar
func NewClientEnvVar() (*Client, error) {
key, err := getApiKey(ApiKeyEnvVar, "")
if err != nil {
return nil, err
}
return &Client{Key: key, URL: flickrURL}, nil
}
func (c *Client) Request(method string, params Params) ([]byte, error) {
url := fmt.Sprintf("%s/?method=flickr.%s&api_key=%s&format=json&nojsoncallback=1", c.URL, method, c.Key)
if len(c.Token) > 0 {
url = fmt.Sprintf("%s&auth_token=%s", url, c.Token)
}
if len(c.Sig) > 0 {
url = fmt.Sprintf("%s&auth_sig=%s", url, c.Sig)
}
for key, value := range params {
url = fmt.Sprintf("%s&%s=%s", url, key, value)
}
response, err := http.Get(url)
if err != nil {
return nil, err
}
if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusPermanentRedirect {
return nil, fmt.Errorf("http status %s", response.Status)
}
defer response.Body.Close()
return ioutil.ReadAll(response.Body)
}