/
api.go
136 lines (96 loc) · 2.24 KB
/
api.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
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
package api
import (
_ "fmt"
"github.com/jeffail/gabs"
"io/ioutil"
"net/http"
"net/url"
)
type APIClient struct {
scheme string
isa string
Host string
Endpoint string
Token string
}
type APIError struct {
Code int64
Message string
}
type APIResponse struct {
Raw []byte
Parsed *gabs.Container
}
func (rsp APIResponse) Stat() string {
var v string
v, _ = rsp.Parsed.Path("stat").Data().(string)
return v
}
func (rsp APIResponse) Ok() (bool, *APIError) {
stat := rsp.Stat()
if stat == "ok" {
return true, nil
}
return false, rsp.Error()
}
func (rsp APIResponse) Error() *APIError {
var code int64
var msg string
// why does this (lookup for error.code) always return 0?
code, _ = rsp.Parsed.Path("error.code").Data().(int64)
msg, _ = rsp.Parsed.Path("error.message").Data().(string)
err := APIError{Code: code, Message: msg}
return &err
}
func (rsp APIResponse) Body() *gabs.Container {
return rsp.Parsed
}
func (rsp APIResponse) Dumps() string {
return rsp.Parsed.String()
}
func ParseAPIResponse(raw []byte) (*APIResponse, error) {
parsed, parse_err := gabs.ParseJSON(raw)
if parse_err != nil {
return nil, parse_err
}
rsp := APIResponse{
Raw: raw,
Parsed: parsed,
}
return &rsp, nil
}
func OAuth2Client(token string) *APIClient {
return &APIClient{
isa: "oauth2",
scheme: "https",
Token: token,
Host: "api.collection.cooperhewitt.org",
Endpoint: "rest/",
}
}
func (client *APIClient) ExecuteMethod(method string, params *url.Values) (*APIResponse, error) {
url := client.scheme + "://" + client.Host + "/" + client.Endpoint
params.Set("method", method)
params.Set("access_token", client.Token)
http_req, req_err := http.NewRequest("POST", url, nil)
if req_err != nil {
return nil, req_err
}
http_req.URL.RawQuery = (*params).Encode()
http_req.Header.Add("Accept-Encoding", "gzip")
http_client := &http.Client{}
http_rsp, http_err := http_client.Do(http_req)
if http_err != nil {
return nil, http_err
}
defer http_rsp.Body.Close()
http_body, io_err := ioutil.ReadAll(http_rsp.Body)
if io_err != nil {
return nil, io_err
}
rsp, parse_err := ParseAPIResponse(http_body)
if parse_err != nil {
return nil, parse_err
}
return rsp, nil
}