-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhttp.go
86 lines (68 loc) · 1.76 KB
/
http.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
package kredivo
import (
"encoding/json"
"io"
"net/http"
"time"
)
// httpRequest data model
type kredivoHttpClient struct {
httpClient *http.Client
}
// newRequest function for intialize httpRequest object
// Paramter, timeout in time.Duration
func newRequest(timeout time.Duration) *kredivoHttpClient {
return &kredivoHttpClient{
httpClient: &http.Client{Timeout: time.Second * timeout},
}
}
// newReq function for initalize http request,
// paramters, http method, uri path, body, and headers
func (c *kredivoHttpClient) newReq(method string, fullPath string, body io.Reader, headers map[string]string) (*http.Request, error) {
req, err := http.NewRequest(method, fullPath, body)
if err != nil {
return nil, err
}
for key, value := range headers {
req.Header.Set(key, value)
}
return req, nil
}
// exec private function for call http request
func (c *kredivoHttpClient) exec(method, path string, body io.Reader, v interface{}, headers map[string]string) error {
req, err := c.newReq(method, path, body, headers)
if err != nil {
return err
}
res, err := c.httpClient.Do(req)
defer res.Body.Close()
if err != nil {
return err
}
if v != nil {
return json.NewDecoder(res.Body).Decode(v)
}
return nil
}
// execAsync private function for call http request with async
func (c *kredivoHttpClient) execAsync(method, path string, body io.Reader, v interface{}, headers map[string]string) <-chan error {
output := make(chan error, 1)
go func() {
req, err := c.newReq(method, path, body, headers)
if err != nil {
output <- err
return
}
res, err := c.httpClient.Do(req)
defer res.Body.Close()
if err != nil {
output <- err
return
}
if v != nil {
output <- json.NewDecoder(res.Body).Decode(v)
return
}
}()
return output
}