-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
executable file
·234 lines (199 loc) · 4.77 KB
/
client.go
File metadata and controls
executable file
·234 lines (199 loc) · 4.77 KB
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
package rubik
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"reflect"
"time"
)
// Client is the implementation for rubik project to create
// a common abstraction of HTTP calls by passing defined entity
type Client struct {
httpClient http.Client
url string
Debug bool
JWTSecret string
BasicSecret string
BearerName string
UserAgent string
}
// Response is a struct that is returned by every client after
// request is made successful
type Response struct {
Status int
Body interface{}
Raw *http.Response
ParsedBody interface{}
StringBody string
IsJSON bool
}
const (
// GET method
GET = "GET"
// POST method
POST = "POST"
// PUT method
PUT = "PUT"
// DELETE method
DELETE = "DELETE"
)
// Payload holds the data between the intermediate state of Client
// and PostProcessor
type Payload struct {
client http.Client
base string
path string
requestType string
json bool
urlencoded bool
formData bool
headers url.Values
params []string
body Values
query url.Values
formBody *bytes.Buffer
rawBody []byte
responseType interface{}
cancel context.CancelFunc
context context.Context
agent string
}
// NewClient creates a new instance of rubik client
func NewClient(baseURL string, timeout time.Duration) *Client {
return &Client{
url: baseURL,
httpClient: http.Client{
Timeout: timeout,
},
BearerName: "Bearer",
}
}
// Get ...
func (c *Client) Get(entity interface{}) (Response, error) {
req, err := populateRequest(entity, c)
if err != nil {
return Response{}, err
}
req.requestType = GET
return call(req)
}
// Post ...
func (c *Client) Post(entity interface{}) (Response, error) {
req, err := populateRequest(entity, c)
if err != nil {
return Response{}, err
}
req.requestType = POST
return call(req)
}
// Put ...
func (c *Client) Put(entity interface{}) (Response, error) {
req, err := populateRequest(entity, c)
if err != nil {
return Response{}, err
}
req.requestType = PUT
return call(req)
}
// Delete ...
func (c *Client) Delete(entity interface{}) (Response, error) {
req, err := populateRequest(entity, c)
if err != nil {
return Response{}, err
}
req.requestType = DELETE
return call(req)
}
// Download method downloads file from an url from your specified Entity->Route
// to TargetFilePath passed to the entity
func (c *Client) Download(entity DownloadRequestEntity) ([]byte, error) {
if entity.PointTo == "" {
errMsg := "DownloadRequestEntity must have a route initialized using Route() method"
return nil, errors.New(errMsg)
}
// source
finalURL := c.url + safeRoutePath(entity.PointTo)
raw, err := downloadCall(finalURL, entity.TargetFilePath)
if err != nil {
return nil, err
}
return raw, nil
}
// Cancel ...
func (r *Payload) Cancel() {
r.cancel()
}
func downloadCall(url, target string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, errors.New("DownloadError: Cannot download file. Raw: " + err.Error())
}
defer resp.Body.Close()
out, err := os.Create(target)
if err != nil {
return nil, errors.New("DownloadError: Cannot create target file. Raw: " + err.Error())
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return nil, errors.New("DownloadError: Cannot copy to target file. Raw: " + err.Error())
}
b, err := ioutil.ReadFile(target)
if err != nil {
return nil, err
}
return b, nil
}
func call(req *Payload) (Response, error) {
fullURL, err := populateParamsAndQuery(req)
if err != nil {
return Response{}, err
}
httpRequest, err := populateHTTPRequest(req, fullURL)
if err != nil {
return Response{}, err
}
resp, err := req.client.Do(httpRequest)
if err != nil {
return Response{}, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// this means that you want ink to infer something
if req.responseType != nil {
responseType := reflect.TypeOf(req.responseType)
err = json.Unmarshal(body, req.responseType)
if err != nil {
errMsg := "InferenceError: Cannot infer a non-json/non-mappable value to " +
"specified type: %s. Response.ParsedBody/Response.StringBody of type map is " +
"present for access."
message := fmt.Sprintf(errMsg, responseType.Name())
return Response{
Status: resp.StatusCode,
IsJSON: false,
StringBody: string(body),
}, errors.New(message)
}
return Response{
Status: resp.StatusCode,
Raw: resp,
IsJSON: true,
ParsedBody: req.responseType,
StringBody: string(body),
}, nil
}
return Response{
Status: resp.StatusCode,
Raw: resp,
IsJSON: false,
ParsedBody: req.responseType,
StringBody: string(body),
}, nil
}