/
request.go
69 lines (62 loc) · 1.46 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
package kong
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/google/go-querystring/query"
)
// NewRequestRaw creates a request based on the inputs.
func (c *Client) NewRequestRaw(method, baseURL string, endpoint string, qs interface{},
body interface{},
) (*http.Request, error) {
if endpoint == "" {
return nil, fmt.Errorf("endpoint can't be nil")
}
// body to be sent in JSON
var r io.Reader
if body != nil {
switch v := body.(type) {
case string:
r = bytes.NewBufferString(v)
case []byte:
r = bytes.NewBuffer(v)
case io.Reader:
r = v
default:
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
r = bytes.NewBuffer(b)
}
}
// Create a new request
req, err := http.NewRequest(method, baseURL+endpoint, r)
if err != nil {
return nil, err
}
// add body if needed
if body != nil {
req.Header.Add("Content-Type", "application/json")
}
// add query string if any
if qs != nil {
values, err := query.Values(qs)
if err != nil {
return nil, err
}
req.URL.RawQuery = values.Encode()
}
return req, nil
}
// NewRequest creates a request based on the inputs.
// endpoint should be relative to the baseURL specified during
// client creation.
// body is always marshaled into JSON.
func (c *Client) NewRequest(method, endpoint string, qs interface{},
body interface{},
) (*http.Request, error) {
return c.NewRequestRaw(method, c.workspacedBaseURL(c.Workspace()), endpoint, qs, body)
}