-
Notifications
You must be signed in to change notification settings - Fork 0
/
Requests.go
335 lines (278 loc) · 7.29 KB
/
Requests.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package libremotebuild
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"strconv"
"time"
)
// Method http request method
type Method string
// Requests
const (
GET Method = "GET"
POST Method = "POST"
DELETE Method = "DELETE"
PUT Method = "PUT"
)
// ContentType contenttype header of request
type ContentType string
// Content types
const (
JSONContentType ContentType = "application/json"
)
// PingRequest a ping request content
type PingRequest struct {
Payload string
}
// Endpoint a remote url-path
type Endpoint string
// Remote endpoints
const (
// Ping
EPPing Endpoint = "/ping"
// User
EPUser Endpoint = "/user"
EPLogin = EPUser + "/login"
EPRegister = EPUser + "/register"
// Jobs
EPJob Endpoint = "/job"
EPJobAdd = EPJob + "/create"
EPJobLogs = EPJob + "/logs"
EPJobCancel = EPJob + "/cancel"
EPJobInfo = EPJob + "/info"
EPJobs = EPJob + "s"
EPJobState = EPJob + "/state"
EPJobPause = EPJobState + "/pause"
EPJobResume = EPJobState + "/resume"
// Ccache
EPCcache Endpoint = "/ccache"
EPCcacheClear = EPCcache + "/clear"
EPCcacheStats = EPCcache + "/stats"
)
// RequestConfig configurations for requests
type RequestConfig struct {
IgnoreCert bool
URL string
MachineID string
Username string
SessionToken string
}
// GetBearerAuth returns bearer authorization from config
func (rc RequestConfig) GetBearerAuth() Authorization {
return Authorization{
Type: Bearer,
Palyoad: rc.SessionToken,
}
}
// Request a rest server request
type Request struct {
RequestType RequestType
Endpoint Endpoint
Payload interface{}
Config *RequestConfig
Method Method
ContentType ContentType
Authorization *Authorization
Headers map[string]string
BenchChan chan time.Time
CloseBody bool
}
// CredentialsRequest request containing credentials
type CredentialsRequest struct {
MachineID string `json:"mid,omitempty"`
Username string `json:"username"`
Password string `json:"pass"`
}
// AddJobRequest request for creating a new job
type AddJobRequest struct {
Type JobType `json:"buildtype"`
Args map[string]string `json:"args"`
UploadType UploadType `json:"uploadtype"`
DisableCcache bool `json:"disableccache"`
}
// JobRequest cancel a job
type JobRequest struct {
JobID uint `json:"id"`
}
// JobLogsRequest cancel a job
type JobLogsRequest struct {
JobID uint `json:"id"`
Since time.Time `json:"since"`
}
// ListJobsRequest request for listing jobs
type ListJobsRequest struct {
Limit int `json:"l"`
}
// RequestType type of request
type RequestType uint8
// Request types
const (
JSONRequestType RequestType = iota
RawRequestType
)
// NewRequest creates a new post request
func (limdm *LibRB) NewRequest(endpoint Endpoint, payload interface{}) *Request {
return &Request{
RequestType: JSONRequestType,
Endpoint: endpoint,
Payload: payload,
Config: limdm.Config,
Method: POST,
ContentType: JSONContentType,
CloseBody: true,
}
}
// WithNoBodyClose don't close body after request
func (request *Request) WithNoBodyClose() *Request {
request.CloseBody = false
return request
}
// WithMethod use a different method
func (request *Request) WithMethod(m Method) *Request {
request.Method = m
return request
}
// WithRequestType use different request type
func (request *Request) WithRequestType(rType RequestType) *Request {
request.RequestType = rType
return request
}
// WithAuth with authorization
func (request *Request) WithAuth(a Authorization) *Request {
request.Authorization = &a
return request
}
// WithAuthFromConfig with authorization
func (request *Request) WithAuthFromConfig() *Request {
auth := request.Config.GetBearerAuth()
request.Authorization = &auth
return request
}
// WithBenchCallback with bench
func (request *Request) WithBenchCallback(c chan time.Time) *Request {
request.BenchChan = c
return request
}
// WithContentType with contenttype
func (request *Request) WithContentType(ct ContentType) *Request {
request.ContentType = ct
return request
}
// WithHeader add header to request
func (request *Request) WithHeader(name string, value string) *Request {
if request.Headers == nil {
request.Headers = make(map[string]string)
}
request.Headers[name] = value
return request
}
// BuildClient return client
func (request *Request) BuildClient() *http.Client {
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: request.Config.IgnoreCert,
},
},
Timeout: 0,
}
}
// DoHTTPRequest do plain http request
func (request *Request) DoHTTPRequest() (*http.Response, error) {
client := request.BuildClient()
// Build url
u, err := url.Parse(request.Config.URL)
if err != nil {
return nil, err
}
u.Path = path.Join(u.Path, string(request.Endpoint))
var reader io.Reader
// Use correct payload
if request.RequestType == JSONRequestType {
// Encode data
var err error
bytePayload, err := json.Marshal(request.Payload)
if err != nil {
return nil, err
}
reader = bytes.NewReader(bytePayload)
} else if request.RequestType == RawRequestType {
switch request.Payload.(type) {
case []byte:
reader = bytes.NewReader((request.Payload).([]byte))
case io.Reader:
reader = (request.Payload).(io.Reader)
case io.PipeReader:
reader = (request.Payload).(*io.PipeReader)
}
}
if reader == nil {
reader = bytes.NewBuffer([]byte(""))
}
// Bulid request
req, _ := http.NewRequest(string(request.Method), u.String(), reader)
// Set contenttype header
req.Header.Set("Content-Type", string(request.ContentType))
for headerKey, headerValue := range request.Headers {
req.Header.Set(headerKey, headerValue)
}
// Set Authorization header
if request.Authorization != nil {
req.Header.Set("Authorization", fmt.Sprintf("%s %s", string(request.Authorization.Type), request.Authorization.Palyoad))
}
return client.Do(req)
}
// Do a better request method
func (request Request) Do(retVar interface{}) (*RestRequestResponse, error) {
resp, err := request.DoHTTPRequest()
// Call bench callbac
if request.BenchChan != nil {
request.BenchChan <- time.Now()
}
if err != nil {
return nil, err
}
var response *RestRequestResponse
response = &RestRequestResponse{
HTTPCode: resp.StatusCode,
Headers: &resp.Header,
}
// Read and validate headers
statusStr := resp.Header.Get(HeaderStatus)
statusMessage := resp.Header.Get(HeaderStatusMessage)
if len(statusStr) == 0 {
return response, ErrInvalidResponseHeaders
}
statusInt, err := strconv.Atoi(statusStr)
if err != nil || (statusInt > 1 || statusInt < 0) {
return response, ErrInvalidResponseHeaders
}
response.Status = (ResponseStatus)(uint8(statusInt))
response.Message = statusMessage
// Only fill retVar if response was successful
if response.Status == ResponseSuccess && retVar != nil {
// Read response
d, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// Parse response into retVar
err = json.Unmarshal(d, &retVar)
if err != nil {
return nil, err
}
}
// Set response
response.Response = resp
if request.CloseBody {
resp.Body.Close()
}
return response, nil
}