-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathrequest.go
74 lines (59 loc) · 1.47 KB
/
request.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
package dialogflow
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
. "github.com/mlabouardy/dialogflow-go-client/models"
)
type Request struct {
URI string
Method string
Headers map[string]string
Body interface{}
QueryParams map[string]string
}
// Initialize a new HTTP request
func NewRequest(client *DialogFlowClient, overridedRequestOptions RequestOptions) *Request {
headers := map[string]string{
"Authorization": "Bearer " + client.GetAccessToken(),
"Content-Type": "application/json",
"Accept": "application/json",
}
request := &Request{
URI: overridedRequestOptions.URI,
Method: overridedRequestOptions.Method,
Headers: headers,
QueryParams: overridedRequestOptions.QueryParams,
Body: overridedRequestOptions.Body,
}
return request
}
// Execute an HTTP request
func (r *Request) Perform() ([]byte, error) {
var data []byte
client := &http.Client{}
req, err := http.NewRequest(r.Method, r.URI, nil)
if r.Method != "GET" {
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(r.Body)
req, err = http.NewRequest(r.Method, r.URI, b)
}
for k, v := range r.Headers {
req.Header.Add(k, v)
}
query := req.URL.Query()
for key, value := range r.QueryParams {
query.Add(key, value)
}
req.URL.RawQuery = query.Encode()
if err != nil {
return data, err
}
resp, err := client.Do(req)
if err != nil {
return data, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}