-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
64 lines (50 loc) · 1.38 KB
/
helper.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
package gOanda
import (
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
)
type method string
func (m method) String() string {
return string(m)
}
const GET method = "GET"
const POST method = "POST"
const PATCH method = "PATCH"
const PUT method = "PUT"
func HttpRequestWrapper(method method, url string, requestBody interface{}, response interface{}, token string) error {
var body io.Reader
if requestBody != nil {
marshaledBody, err := json.Marshal(requestBody)
if err != nil {
return err
}
body = bytes.NewBuffer(marshaledBody)
}
httpRequest, err := http.NewRequest(method.String(), url, body)
if err != nil {
return errors.New("could not create new HTTP request: " + err.Error())
}
httpRequest.Header.Add("Content-type", "application/json")
if token != "" {
httpRequest.Header.Add("Authorization", "Bearer "+token)
}
httpResponse, err := http.DefaultClient.Do(httpRequest)
if err != nil {
return errors.New("could not send HTTP request: " + err.Error())
}
defer httpResponse.Body.Close()
responseBody, err := ioutil.ReadAll(httpResponse.Body)
if err != nil {
return errors.New("could not read body of response: " + err.Error())
}
err = json.Unmarshal(responseBody, response)
//fmt.Println("Response: ", string(responseBody))
if err != nil {
return errors.New("could not unmarshal the body of the response: " + err.Error())
}
return nil
}