-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmirage.go
237 lines (184 loc) · 5.22 KB
/
mirage.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
// go-mirage-api
//
// Copyright 2023, Valerian Saliou
// Author: Valerian Saliou <[email protected]>
package mirage
import (
"bytes"
"encoding/json"
"fmt"
"time"
"io"
"errors"
"io/ioutil"
"net/http"
"net/url"
)
const (
libraryVersion = "1.10.1"
defaultRestEndpointURL = "https://api.mirage-ai.com/v1/"
userAgent = "go-mirage-api/" + libraryVersion
acceptContentType = "application/json"
clientTimeout = 40
clientIdleConnTimeout = 45
clientMaxIdleConns = 16
clientMaxConnsPerHost = 64
clientMaxIdleConnsPerHost = 4
)
var errorDoNilRequest = errors.New("request could not be constructed")
// ClientConfig mapping
type ClientConfig struct {
HTTPClient *http.Client
RestEndpointURL string
}
type auth struct {
Username string
Password string
}
// Client maps an API client
type Client struct {
config *ClientConfig
client *http.Client
auth *auth
BaseURL *url.URL
UserAgent string
common service
Task *TaskService
Data *DataService
}
type service struct {
client *Client
}
// RequestContext maps custom context for a request
type RequestContext struct {
Trace string `json:"string"`
}
// Response maps an API HTTP response
type Response struct {
*http.Response
}
type errorResponse struct {
Response *http.Response
Reason string `json:"reason,omitempty"`
Message string `json:"message,omitempty"`
}
// Error prints an error response
func (response *errorResponse) Error() string {
return fmt.Sprintf("%v %v: %d %v",
response.Response.Request.Method, response.Response.Request.URL,
response.Response.StatusCode, response.Reason)
}
// NewWithConfig returns a new API client
func NewWithConfig(userID string, secretKey string, config ClientConfig) *Client {
// Defaults
if config.HTTPClient == nil {
// Build client transport
clientTransport := http.DefaultTransport.(*http.Transport).Clone()
clientTransport.IdleConnTimeout = time.Duration(clientIdleConnTimeout * time.Second)
clientTransport.MaxIdleConns = clientMaxIdleConns
clientTransport.MaxConnsPerHost = clientMaxConnsPerHost
clientTransport.MaxIdleConnsPerHost = clientMaxIdleConnsPerHost
// Create client
config.HTTPClient = &http.Client{
Timeout: time.Duration(clientTimeout * time.Second),
Transport: clientTransport,
}
}
if config.RestEndpointURL == "" {
config.RestEndpointURL = defaultRestEndpointURL
}
// Create client
baseURL, _ := url.Parse(config.RestEndpointURL)
client := &Client{config: &config, client: config.HTTPClient, auth: &auth{userID, secretKey}, BaseURL: baseURL, UserAgent: userAgent}
client.common.client = client
// Map services
client.Task = (*TaskService)(&client.common)
client.Data = (*DataService)(&client.common)
return client
}
// New returns a new API client
func New(userID string, secretKey string) *Client {
return NewWithConfig(userID, secretKey, ClientConfig{})
}
// NewRequest creates an API request
func (client *Client) NewRequest(method, urlStr string, body interface{}, ctx RequestContext) (*http.Request, error) {
rel, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
url := client.BaseURL.ResolveReference(rel)
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, url.String(), buf)
if err != nil {
return nil, err
}
req.SetBasicAuth(client.auth.Username, client.auth.Password)
req.Header.Add("Accept", acceptContentType)
req.Header.Add("Content-Type", acceptContentType)
if client.UserAgent != "" {
req.Header.Add("User-Agent", client.UserAgent)
}
if ctx.Trace != "" {
// Stamp request with provided trace identifier (this is optional, but \
// can be used to track request flows across Mirage backend systems, for \
// debugging purposes)
req.Header.Add("X-Request-ID", ctx.Trace)
}
return req, nil
}
// Do sends an API request
func (client *Client) Do(req *http.Request, v interface{}) (*Response, error) {
if req == nil {
return nil, errorDoNilRequest
}
resp, err := client.client.Do(req)
if err != nil {
return nil, err
}
defer func() {
io.CopyN(ioutil.Discard, resp.Body, 512)
resp.Body.Close()
}()
response := newResponse(resp)
err = checkResponse(resp)
if err != nil {
return response, err
}
if v != nil {
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(v)
if err == io.EOF {
err = nil
}
}
}
return response, err
}
// newResponse creates an HTTP response
func newResponse(httpResponse *http.Response) *Response {
response := &Response{Response: httpResponse}
return response
}
// checkResponse checks response for errors
func checkResponse(response *http.Response) error {
// No error in response? (HTTP 2xx)
if code := response.StatusCode; 200 <= code && code <= 299 {
return nil
}
// Map response error data (eg. HTTP 4xx)
errorResponse := &errorResponse{Response: response}
data, err := ioutil.ReadAll(response.Body)
if err == nil && data != nil {
json.Unmarshal(data, errorResponse)
}
return errorResponse
}