-
Notifications
You must be signed in to change notification settings - Fork 5
/
requests.go
221 lines (190 loc) · 6.69 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
package taigo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strconv"
)
// Evaluation Tools
var httpSuccessCodes = [...]int{
http.StatusOK,
http.StatusCreated,
http.StatusAccepted,
http.StatusNoContent,
}
// RequestService is a handle to HTTP request operations
type RequestService struct {
client *Client
}
// SuccessfulHTTPRequest returns true if the given Response's StatusCode
// is one of `[...]int{200, 201, 202, 204}`; otherwise returns false
// Taiga does not return status codes other than above stated
func SuccessfulHTTPRequest(Response *http.Response) bool {
for _, code := range httpSuccessCodes {
if Response.StatusCode == code {
return true
}
}
return false
}
// Get a handler for composing a new HTTP GET request
//
// * URL must be an absolute (full) URL to the desired endpoint
// * ResponseBody must be a pointer to a struct representing the fields returned by Taiga
func (s *RequestService) Get(URL string, ResponseBody interface{}) (*http.Response, error) {
return newRawRequest("GET", s.client, ResponseBody, URL, nil)
}
// Head a handler for composing a new HTTP HEAD request
func (s *RequestService) Head() {
panic("HEAD requests are not implemented")
}
// Post a handler for composing a new HTTP POST request
//
// * URL must be an absolute (full) URL to the desired endpoint
// * Payload must be a pointer to a complete struct which will be sent to Taiga
// * ResponseBody must be a pointer to a struct representing the fields returned by Taiga
func (s *RequestService) Post(URL string, Payload interface{}, ResponseBody interface{}) (*http.Response, error) {
return newRawRequest("POST", s.client, ResponseBody, URL, Payload)
}
// Put a handler for composing a new HTTP PUT request
//
// * URL must be an absolute (full) URL to the desired endpoint
// * Payload must be a pointer to a complete struct which will be sent to Taiga
// * ResponseBody must be a pointer to a struct representing the fields returned by Taiga
func (s *RequestService) Put(URL string, Payload interface{}, ResponseBody interface{}) (*http.Response, error) {
return newRawRequest("PUT", s.client, ResponseBody, URL, Payload)
}
// Patch a handler for composing a new HTTP PATCH request
//
// * URL must be an absolute (full) URL to the desired endpoint
// * Payload must be a pointer to a complete struct which will be sent to Taiga
// * ResponseBody must be a pointer to a struct representing the fields returned by Taiga
func (s *RequestService) Patch(URL string, Payload interface{}, ResponseBody interface{}) (*http.Response, error) {
return newRawRequest("PATCH", s.client, ResponseBody, URL, Payload)
}
// Delete a handler for composing a new HTTP DELETE request
//
// * URL must be an absolute (full) URL to the desired endpoint
func (s *RequestService) Delete(URL string) (*http.Response, error) {
return newRawRequest("DELETE", s.client, nil, URL, nil)
}
// Connect a handler for composing a new HTTP CONNECT request
func (s *RequestService) Connect() {
panic("CONNECT requests are not implemented")
}
// Options a handler for composing a new HTTP OPTIONS request
func (s *RequestService) Options() {
panic("OPTIONS requests are not implemented")
}
// Trace a handler for composing a new HTTP TRACE request
func (s *RequestService) Trace() {
panic("TRACE requests are not implemented")
}
// NOTE: responseBody must always be a pointer otherwise we lose the response data!
func newfileUploadRequest(c *Client, url string, attachment *Attachment, tgObject TaigaBaseObject) (*Attachment, error) {
// Map Object details into *Attachment
attachment.ObjectID = tgObject.GetID()
attachment.Project = tgObject.GetProject()
// Open file
f, err := os.Open(attachment.filePath)
if err != nil {
return nil, fmt.Errorf("Could not open file at specified location: " + attachment.filePath)
}
fileName := filepath.Base(attachment.filePath)
defer f.Close()
// Prepare request body
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("attached_file", fileName)
if err != nil {
return nil, fmt.Errorf("could not write file to buffer")
}
io.Copy(part, f)
// Add object_id & project to the form-data
writer.WriteField("object_id", strconv.Itoa(attachment.ObjectID))
writer.WriteField("project", strconv.Itoa(attachment.Project))
writer.WriteField("from_comment", "False")
writer.Close()
// Create POST Request
request, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
// Add headers (manually, not calling c.loadHeaders())
request.Header.Set("Authorization", c.GetAuthorizationHeader()) // Load token
request.Header.Set("Content-Type", writer.FormDataContentType()) // Set Content-Type to multipart/form-data
// Execute Request
rawResponse, err := c.HTTPClient.Do(request)
// c.setContentTypeToJSON() // Reset (just in case..)
if err != nil {
return nil, err
}
defer rawResponse.Body.Close()
// Evaluate response status code && return response
rawResponseBody, err := ioutil.ReadAll(rawResponse.Body)
if err != nil {
return nil, err
}
if SuccessfulHTTPRequest(rawResponse) {
var responseBody Attachment
// We expect content so convert response JSON string to struct
json.Unmarshal([]byte(rawResponseBody), &responseBody) // responseBody contains a pointer to a struct
return &responseBody, nil
}
return nil, fmt.Errorf(string(rawResponseBody))
}
func newRawRequest(RequestType string, c *Client, ResponseBody interface{}, URL string, Payload interface{}) (*http.Response, error) {
// New RAW request
var request *http.Request
var err error
switch {
case Payload == nil:
request, err = http.NewRequest(RequestType, URL, nil)
if err != nil {
return nil, err
}
case Payload != nil:
body, err := json.Marshal(Payload)
if err != nil {
return nil, err
}
request, err = http.NewRequest(RequestType, URL, bytes.NewBuffer(body))
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("failed to build request because the received payload could not be processed")
}
// Load Headers
c.loadHeaders(request)
// Execute request
resp, err := c.HTTPClient.Do(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Evaluate response status code
if SuccessfulHTTPRequest(resp) {
if resp.StatusCode == http.StatusNoContent { // There's no body returned for 204 responses
return resp, nil
}
// We expect content so convert response JSON string to struct
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&ResponseBody)
if err != nil {
return nil, err
}
return resp, nil
}
rawResponseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf(string(rawResponseBody))
}