-
Notifications
You must be signed in to change notification settings - Fork 3
/
http.go
58 lines (46 loc) · 1.31 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
package ammana
import (
"encoding/json"
"io"
"net/http"
"time"
)
// httpRequest data model
type ammanaHttpClient struct {
httpClient *http.Client
}
// newRequest function for intialize httpRequest object
// Paramter, timeout in time.Duration
func newRequest(timeout time.Duration) *ammanaHttpClient {
return &ammanaHttpClient{
httpClient: &http.Client{Timeout: time.Second * timeout},
}
}
// newReq function for initalize http request,
// paramters, http method, uri path, body, and headers
func (c *ammanaHttpClient) 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 *ammanaHttpClient) 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
}