-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.go
212 lines (180 loc) · 5.78 KB
/
lib.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
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package kittycad
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
)
// DefaultServerURL is the default server URL for the KittyCad API.
const DefaultServerURL = "https://api.zoo.dev"
// TokenEnvVar is the environment variable that contains the token.
const TokenEnvVar = "ZOO_API_TOKEN"
type service struct {
client *Client
}
// NewClient creates a new client for the KittyCad API.
// You need to pass in your API token to create the client.
func NewClient(token, userAgent string) (*Client, error) {
if token == "" {
return nil, fmt.Errorf("you need to pass in an API token to create the client. Create a token at https://zoo.dev/account")
}
client := &Client{
server: DefaultServerURL,
token: token,
}
// Ensure the server URL always has a trailing slash.
if !strings.HasSuffix(client.server, "/") {
client.server += "/"
}
uat := userAgentTransport{
base: http.DefaultTransport,
userAgent: userAgent,
client: client,
}
client.client = &http.Client{
Transport: uat,
// We want a longer timeout since some of the files might take a bit.
Timeout: 600 * time.Second,
}
// Add the services to our client.
client.APICall = &APICallService{client: client}
client.APIToken = &APITokenService{client: client}
client.App = &AppService{client: client}
client.Beta = &BetaService{client: client}
client.Constant = &ConstantService{client: client}
client.Executor = &ExecutorService{client: client}
client.File = &FileService{client: client}
client.Hidden = &HiddenService{client: client}
client.Meta = &MetaService{client: client}
client.Ml = &MlService{client: client}
client.Modeling = &ModelingService{client: client}
client.Oauth2 = &Oauth2Service{client: client}
client.Org = &OrgService{client: client}
client.Payment = &PaymentService{client: client}
client.ServiceAccount = &ServiceAccountService{client: client}
client.Shortlink = &ShortlinkService{client: client}
client.Store = &StoreService{client: client}
client.Unit = &UnitService{client: client}
client.User = &UserService{client: client}
return client, nil
}
// NewClientFromEnv creates a new client for the KittyCad API, using the token
// stored in the environment variable `KITTYCAD_API_TOKEN` or `ZOO_API_TOKEN`.
// Optionally, you can pass in a different base url from the default with `ZOO_HOST`. But that
// is not recommended, unless you know what you are doing or you are hosting
// your own instance of the KittyCAD API.
func NewClientFromEnv(userAgent string) (*Client, error) {
token := os.Getenv(TokenEnvVar)
if token == "" {
// Try the old environment variable name.
token = os.Getenv("KITTYCAD_API_TOKEN")
if token == "" {
return nil, fmt.Errorf("the environment variable %s must be set with your API token. Create a token at https://zoo.dev/account", TokenEnvVar)
}
}
host := os.Getenv("ZOO_HOST")
if host == "" {
host = DefaultServerURL
}
c, err := NewClient(token, userAgent)
if err != nil {
return nil, err
}
c.WithBaseURL(host)
return c, nil
}
// WithBaseURL overrides the baseURL.
func (c *Client) WithBaseURL(baseURL string) error {
newBaseURL, err := url.Parse(baseURL)
if err != nil {
return err
}
c.server = newBaseURL.String()
// Ensure the server URL always has a trailing slash.
if !strings.HasSuffix(c.server, "/") {
c.server += "/"
}
return nil
}
// WithToken overrides the token used for authentication.
func (c *Client) WithToken(token string) {
c.token = token
}
type userAgentTransport struct {
userAgent string
base http.RoundTripper
client *Client
}
func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.base == nil {
return nil, errors.New("RoundTrip: no Transport specified")
}
newReq := *req
newReq.Header = make(http.Header)
for k, vv := range req.Header {
newReq.Header[k] = vv
}
// Add the user agent header.
newReq.Header["User-Agent"] = []string{t.userAgent}
// Add the content-type header.
newReq.Header["Content-Type"] = []string{"application/json"}
// Add the authorization header.
newReq.Header["Authorization"] = []string{fmt.Sprintf("Bearer %s", t.client.token)}
return t.base.RoundTrip(&newReq)
}
// HTTPError is an error returned by a failed API call.
type HTTPError struct {
// URL is the URL that was being accessed when the error occurred.
// It will always be populated.
URL *url.URL
// StatusCode is the HTTP response status code and will always be populated.
StatusCode int
// Message is the server response message and is only populated when
// explicitly referenced by the JSON server response.
Message string
// Body is the raw response returned by the server.
// It is often but not always JSON, depending on how the request fails.
Body string
// Header contains the response header fields from the server.
Header http.Header
}
// Error converts the Error type to a readable string.
func (err HTTPError) Error() string {
if err.Message != "" {
return fmt.Sprintf("HTTP %d: %s (%s)", err.StatusCode, err.Message, err.URL)
}
return fmt.Sprintf("HTTP %d (%s) BODY -> %v", err.StatusCode, err.URL, err.Body)
}
// checkResponse returns an error (of type *HTTPError) if the response
// status code is not 2xx.
func checkResponse(res *http.Response) error {
if res.StatusCode >= 200 && res.StatusCode <= 299 {
return nil
}
slurp, err := io.ReadAll(res.Body)
if err == nil {
var jerr Error
// Try to decode the body as an ErrorMessage.
if err := json.Unmarshal(slurp, &jerr); err == nil {
return &HTTPError{
URL: res.Request.URL,
StatusCode: res.StatusCode,
Message: jerr.Message,
Body: string(slurp),
Header: res.Header,
}
}
}
return &HTTPError{
URL: res.Request.URL,
StatusCode: res.StatusCode,
Body: string(slurp),
Header: res.Header,
Message: "",
}
}