-
Notifications
You must be signed in to change notification settings - Fork 1
/
restclient.go
94 lines (77 loc) · 2.04 KB
/
restclient.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
package oxxopay
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strings"
)
// RequestData
//
// Map data por post in the request
type RequestData map[string]interface{}
// RequestHeaders
//
// Map extra request headers
type RequestHeaders map[string]string
// RestClient
//
// Main structure for rest request
type RestClient struct{}
// Execute
//
// Make request and return the response
func (rest *RestClient) Execute(method string, url string, data RequestData, headers RequestHeaders) ([]byte, error) {
if method != "GET" && method != "POST" && method != "PUT" && method != "DELETE" {
return nil, errors.New("rest: Not supported method")
}
var payload *strings.Reader
if data != nil {
payloadByte, err := json.Marshal(data)
if err != nil {
return nil, err
}
payload = strings.NewReader(string(payloadByte))
} else {
payload = strings.NewReader("")
}
req, _ := http.NewRequest(method, url, payload)
req.Header.Add("content-type", "application/json")
req.Header.Add("accept", "application/json")
if headers != nil {
for key, value := range headers {
req.Header.Add(key, value)
}
}
res, errReq := http.DefaultClient.Do(req)
if errReq != nil {
return nil, errReq
}
defer res.Body.Close()
body, errRead := ioutil.ReadAll(res.Body)
return body, errRead
}
// Get
//
// Execute only Get request
func (rest *RestClient) Get(url string, data RequestData, headers RequestHeaders) ([]byte, error) {
return rest.Execute("GET", url, data, headers)
}
// Post
//
// Execute only Post request
func (rest *RestClient) Post(url string, data RequestData, headers RequestHeaders) ([]byte, error) {
return rest.Execute("POST", url, data, headers)
}
// Put
//
// Execute only put request
func (rest *RestClient) Put(url string, data RequestData, headers RequestHeaders) ([]byte, error) {
return rest.Execute("PUT", url, data, headers)
}
// Delete
//
// Execute only delete request
func (rest *RestClient) Delete(url string, data RequestData, headers RequestHeaders) ([]byte, error) {
return rest.Execute("DELETE", url, data, headers)
}