-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_oauth_client.go
64 lines (58 loc) · 1.58 KB
/
http_oauth_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
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"github.com/dghubble/oauth1"
)
type httpOAuthClient struct {
accessToken string
accessSecret string
oauthConfig oauth1.Config
}
func newHTTPOAuthClient(aT string, aS string, oC oauth1.Config) *httpOAuthClient {
hoc := new(httpOAuthClient)
hoc.accessToken = aT
hoc.accessSecret = aS
hoc.oauthConfig = oC
return hoc
}
func (hoc *httpOAuthClient) getMarshalledAPIResponse(url string, responseContainer interface{}) error {
token := oauth1.NewToken(hoc.accessToken, hoc.accessSecret)
// httpClient will automatically authorize http.Request's
httpClient := hoc.oauthConfig.Client(oauth1.NoContext, token)
resp, err := httpClient.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, responseContainer)
if err != nil {
return err
}
return nil
}
func (hoc *httpOAuthClient) postResource(url string, resource interface{},
responseContainer interface{}) error {
token := oauth1.NewToken(hoc.accessToken, hoc.accessSecret)
httpClient := hoc.oauthConfig.Client(oauth1.NoContext, token)
requestBody, err := json.Marshal(resource)
if err != nil {
return err
}
resp, err := httpClient.Post(url, "application/json", bytes.NewReader(requestBody))
if err != nil {
return err
}
defer resp.Body.Close()
//Only if respose container is passed response need to be unmarshalled
if responseContainer != nil {
responseBody, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(responseBody, responseContainer)
if err != nil {
return err
}
}
return nil
}