forked from yanatan16/golang-instagram
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.go
More file actions
198 lines (163 loc) · 4.36 KB
/
api.go
File metadata and controls
198 lines (163 loc) · 4.36 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// Package instagram provides a minimialist instagram API wrapper.
package instagram
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"sort"
)
var (
baseURL = "https://api.instagram.com/v1"
)
// API is the Instagram API.
type API struct {
ClientID string
ClientSecret string
AccessToken string
EnforceSignedRequest bool
// HTTPClient sets a custom HTTP Client used to make requests.
HTTPClient *http.Client
// KeepRawBody set to true will store the raw API response body
// of the last request in RawBody.
KeepRawBody bool
RawBody io.Reader
// Header contains the raw API response header of the last request.
Header http.Header
}
// New creates an API with either a ClientID OR an accessToken. Only one is
// required. Access tokens are preferred because they keep rate limiting down.
// If enforceSignedRequest is set to true, then clientSecret is required
func New(clientID string, clientSecret string, accessToken string, enforceSignedRequest bool) *API {
if clientID == "" && accessToken == "" {
panic("ClientID or AccessToken must be given to create an API")
}
if enforceSignedRequest && clientSecret == "" {
panic("ClientSecret is required for signed request")
}
return &API{
ClientID: clientID,
ClientSecret: clientSecret,
AccessToken: accessToken,
HTTPClient: &http.Client{},
EnforceSignedRequest: enforceSignedRequest,
}
}
// -- Implementation of request --
func signParams(path string, params url.Values, clientSecret string) url.Values {
message := path
keys := []string{}
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
for _, v := range keys {
message += "|" + v + "=" + params.Get(v)
}
hash := hmac.New(sha256.New, []byte(clientSecret))
hash.Write([]byte(message))
params.Set("sig", hex.EncodeToString(hash.Sum(nil)))
return params
}
func buildGetRequest(urlStr string, params url.Values) (*http.Request, error) {
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
// If we are getting, then we can't merge query params
if params != nil {
if u.RawQuery != "" {
return nil, fmt.Errorf("Cannot merge query params in urlStr and params")
}
u.RawQuery = params.Encode()
}
return http.NewRequest("GET", u.String(), nil)
}
func (api *API) extendParams(p url.Values) url.Values {
if p == nil {
p = url.Values{}
}
if api.AccessToken != "" {
p.Set("access_token", api.AccessToken)
} else {
p.Set("client_id", api.ClientID)
}
return p
}
func (api *API) get(ctx context.Context, path string, params url.Values, r interface{}) error {
params = api.extendParams(params)
// Sign request if ForceSignedRequest is set to true
if api.EnforceSignedRequest {
params = signParams(path, params, api.ClientSecret)
}
req, err := buildGetRequest(urlify(path), params)
if err != nil {
return err
}
return api.do(ctx, req, r)
}
func (api *API) do(ctx context.Context, req *http.Request, r interface{}) error {
req = req.WithContext(ctx)
resp, err := api.HTTPClient.Do(req)
if err != nil {
return err
}
defer func() {
io.CopyN(ioutil.Discard, resp.Body, 512)
resp.Body.Close()
}()
api.Header = resp.Header
if resp.StatusCode != 200 {
return api.apiError(resp)
}
return api.decodeResponse(resp.Body, r)
}
func (api *API) decodeResponse(body io.Reader, to interface{}) error {
var r io.Reader
if api.KeepRawBody {
var buf bytes.Buffer
r = io.TeeReader(body, &buf)
api.RawBody = &buf
} else {
r = body
}
err := json.NewDecoder(r).Decode(to)
if err != nil {
return fmt.Errorf("instagram: error decoding body; %s", err.Error())
}
return nil
}
func (api *API) apiError(resp *http.Response) error {
m := new(metaResponse)
if err := api.decodeResponse(resp.Body, m); err != nil {
return err
}
var err MetaError
if m.Meta != nil {
err = MetaError(*m.Meta)
} else {
err = MetaError(Meta{Code: resp.StatusCode, ErrorMessage: resp.Status})
}
return &err
}
func urlify(path string) string {
return baseURL + path
}
// MetaError is an error from response metadata.
type MetaError Meta
func (m *MetaError) Error() string {
return fmt.Sprintf("Error making api call: Code %d %s %s", m.Code, m.ErrorType, m.ErrorMessage)
}
func ensureParams(v url.Values) url.Values {
if v == nil {
return url.Values{}
}
return v
}