-
Notifications
You must be signed in to change notification settings - Fork 0
/
apirequester.go
92 lines (77 loc) · 2.17 KB
/
apirequester.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
package oygo
import (
"bytes"
"context"
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"reflect"
)
// APIRequester abstraction of HTTP Client that will make API calls to OY backend.
// `body` is POST-requests' bodies if applicable.
// `result` pointer to value which response string will be unmarshalled to.
type APIRequester interface {
Call(ctx context.Context, method string, url string, header *http.Header, body interface{}, result interface{}) *Error
}
// APIRequesterImplementation is the default implementation of APIRequester
type APIRequesterImplementation struct {
HTTPClient *http.Client
}
// Call makes HTTP requests with JSON-format body.
// `body` is POST-requests' bodies if applicable.
// `result` pointer to value which response string will be unmarshalled to.
func (a *APIRequesterImplementation) Call(ctx context.Context, method string, url string, header *http.Header, body interface{}, result interface{}) *Error {
reqBody := []byte("")
var req *http.Request
var err error
isParamsNil := body == nil || (reflect.ValueOf(body).Kind() == reflect.Ptr && reflect.ValueOf(body).IsNil())
if !isParamsNil {
reqBody, err = json.Marshal(body)
log.Print(string(reqBody))
if err != nil {
return FromGoErr(err)
}
}
req, err = newHTTPRequestWithContext(
ctx,
method,
url,
bytes.NewBuffer(reqBody),
)
if err != nil {
return FromGoErr(err)
}
if header != nil {
req.Header = *header
}
req.Header.Set("Content-Type", "application/json")
return a.doRequest(req, result)
}
func (a *APIRequesterImplementation) doRequest(req *http.Request, result interface{}) *Error {
resp, err := a.HTTPClient.Do(req)
if err != nil {
return FromGoErr(err)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return FromGoErr(err)
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return FromHTTPErr(resp.StatusCode, respBody)
}
if err := json.Unmarshal(respBody, &result); err != nil {
return FromGoErr(err)
}
return nil
}
func newHTTPRequestWithContext(ctx context.Context, method string, url string, body io.Reader) (*http.Request, error) {
return http.NewRequestWithContext(
ctx,
method,
url,
body,
)
}