-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
82 lines (69 loc) · 1.62 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
81
82
package go_unsplash
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type Options struct {
BaseAPIURL string
AccessKey string
SecretKey string
}
type Client struct {
http *http.Client
req *http.Request
options *Options
baseURL string
}
func NewClient(options *Options) *Client {
r := http.Request{}
r.Header = make(map[string][]string)
r.Header.Add("Authorization", "Client-ID "+options.AccessKey)
return &Client{
http: &http.Client{Timeout: time.Second * 10},
req: &r,
options: options,
baseURL: options.BaseAPIURL,
}
}
func (client *Client) Photos() *PhotosCollection {
return &PhotosCollection{
client: client,
url: fmt.Sprintf("%v/%v", client.baseURL, "search/photos"),
}
}
func (client *Client) Collections() *CollectionsCollection {
return &CollectionsCollection{
client: client,
url: fmt.Sprintf("%v/%v", client.baseURL, "search/collections"),
}
}
func (client *Client) Topics() *TopicsCollection {
return &TopicsCollection{
client: client,
url: fmt.Sprintf("%v/%v", client.baseURL, "topics"),
}
}
func (client *Client) Users() *UsersCollection {
return &UsersCollection{
client: client,
url: fmt.Sprintf("%v/%v", client.baseURL, "search/users"),
}
}
func (client *Client) executeAPICall(result interface{}) (*http.Response, []byte, error) {
response, errGet := client.http.Do(client.req)
if errGet != nil {
return nil, nil, errGet
}
b, errRead := ioutil.ReadAll(response.Body)
if errRead != nil {
return nil, nil, errRead
}
errUnm := json.Unmarshal(b, result)
if errUnm != nil {
return nil, nil, errUnm
}
return response, b, nil
}