-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
104 lines (88 loc) · 2.33 KB
/
request.go
File metadata and controls
104 lines (88 loc) · 2.33 KB
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
94
95
96
97
98
99
100
101
102
103
104
package confluentcloud
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
// Request implements the basic Request function
func (a *api) Request(req *http.Request) ([]byte, error) {
req.Header.Add("Accept", "application/json, */*")
// only auth if we can auth
if (a.username != "") || (a.token != "") {
a.Auth(req)
}
Debug("====== Request ======")
Debug(req)
Debug("====== Request Body ======")
if DebugFlag {
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(requestDump))
}
Debug("====== /Request Body ======")
Debug("====== /Request ======")
resp, err := a.client.Do(req)
if err != nil {
return nil, err
}
Debug(fmt.Sprintf("====== Response Status Code: %d ======", resp.StatusCode))
res, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
resp.Body.Close()
Debug("====== Response Body ======")
Debug(string(res))
Debug("====== /Response Body ======")
switch resp.StatusCode {
case http.StatusOK, http.StatusCreated, http.StatusPartialContent:
return res, nil
case http.StatusNoContent, http.StatusResetContent:
return nil, nil
case http.StatusUnauthorized:
return nil, fmt.Errorf("authentication failed")
case http.StatusServiceUnavailable:
return nil, fmt.Errorf("service is not available: %s", resp.Status)
case http.StatusInternalServerError:
return nil, fmt.Errorf("internal server error: %s", resp.Status)
case http.StatusConflict:
return nil, fmt.Errorf("conflict: %s", resp.Status)
}
return nil, fmt.Errorf("unknown response status: %s", resp.Status)
}
// SendContentRequest sends content related requests
// this function is used for getting, updating and deleting content
func (a *api) SendContentRequest(ep *url.URL, method string, c *Content) (*Content, error) {
var body io.Reader
if c != nil {
js, err := json.Marshal(c)
if err != nil {
return nil, err
}
body = strings.NewReader(string(js))
}
req, err := http.NewRequest(method, ep.String(), body)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Add("Content-Type", "application/json")
}
res, err := a.Request(req)
if err != nil {
return nil, err
}
var content Content
err = json.Unmarshal(res, &content)
if err != nil {
return nil, err
}
return &content, nil
}