-
Notifications
You must be signed in to change notification settings - Fork 15
/
client.go
160 lines (130 loc) · 3.47 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
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
// Package clarifai provides a client interface to the Clarifai public API
package clarifai
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
)
// Configurations
const (
version = "v1"
rootURL = "https://api.clarifai.com"
)
// Client contains scoped variables forindividual clients
type Client struct {
ClientID string
ClientSecret string
AccessToken string
APIRoot string
Throttled bool
}
// TokenResp is the expected response from /token/
type TokenResp struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
TokenType string `json:"token_type"`
}
// NewClient initializes a new Clarifai client
func NewClient(clientID, clientSecret string) *Client {
return &Client{clientID, clientSecret, "unasigned", rootURL, false}
}
func (client *Client) requestAccessToken() error {
form := url.Values{}
form.Set("grant_type", "client_credentials")
form.Set("client_id", client.ClientID)
form.Set("client_secret", client.ClientSecret)
formData := strings.NewReader(form.Encode())
req, err := http.NewRequest("POST", client.buildURL("token"), formData)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+client.AccessToken)
req.Header.Set("Content-Length", strconv.Itoa(len(form.Encode())))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
httpClient := &http.Client{}
res, err := httpClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
token := new(TokenResp)
err = json.Unmarshal(body, token)
if err != nil {
return err
}
client.setAccessToken(token.AccessToken)
return nil
}
func (client *Client) commonHTTPRequest(jsonBody interface{}, endpoint, verb string, retry bool) ([]byte, error) {
if jsonBody == nil {
jsonBody = struct{}{}
}
body, err := json.Marshal(jsonBody)
if err != nil {
return nil, err
}
req, err := http.NewRequest(verb, client.buildURL(endpoint), bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Length", strconv.Itoa(len(body)))
req.Header.Set("Authorization", "Bearer "+client.AccessToken)
req.Header.Set("Content-Type", "application/json")
httpClient := &http.Client{}
res, err := httpClient.Do(req)
if err != nil {
return nil, err
}
switch res.StatusCode {
case 200, 201:
if client.Throttled {
client.setThrottle(false)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
return body, err
case 401:
if !retry {
err := client.requestAccessToken()
if err != nil {
return nil, err
}
return client.commonHTTPRequest(jsonBody, endpoint, verb, true)
}
return nil, errors.New("TOKEN_INVALID")
case 429:
client.setThrottle(true)
return nil, errors.New("THROTTLED")
case 400:
return nil, errors.New("ALL_ERROR")
case 500:
return nil, errors.New("CLARIFAI_ERROR")
default:
return nil, errors.New("UNEXPECTED_STATUS_CODE")
}
}
// Helper function to build URLs
func (client *Client) buildURL(endpoint string) string {
parts := []string{client.APIRoot, version, endpoint}
return strings.Join(parts, "/")
}
// SetAccessToken will set accessToken to a new value
func (client *Client) setAccessToken(token string) {
client.AccessToken = token
}
func (client *Client) setAPIRoot(root string) {
client.APIRoot = root
}
func (client *Client) setThrottle(throttle bool) {
client.Throttled = throttle
}