/
client.go
226 lines (201 loc) · 5.83 KB
/
client.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package zia
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strings"
"time"
"github.com/SecurityGeekIO/zscaler-sdk-go/v2/cache"
"github.com/SecurityGeekIO/zscaler-sdk-go/v2/logger"
"github.com/google/uuid"
)
func (c *Client) do(req *http.Request, start time.Time, reqID string) (*http.Response, error) {
key := cache.CreateCacheKey(req)
if c.cacheEnabled {
if req.Method != http.MethodGet {
// this will allow to remove resource from cache when PUT/DELETE/PATCH requests are called, which modifies the resource
c.cache.Delete(key)
// to avoid resources that GET url is not the same as DELETE/PUT/PATCH url, because of different query params.
// example delete app segment has key url/<id>?forceDelete=true but GET has url/<id>, in this case we clean the whole cache entries with key prefix url/<id>
c.cache.ClearAllKeysWithPrefix(strings.Split(key, "?")[0])
}
resp := c.cache.Get(key)
inCache := resp != nil
if c.freshCache {
c.cache.Delete(key)
inCache = false
c.freshCache = false
}
if inCache {
c.Logger.Printf("[INFO] served from cache, key:%s\n", key)
return resp, nil
}
}
resp, err := c.HTTPClient.Do(req)
logger.LogResponse(c.Logger, resp, start, reqID)
if err != nil {
return resp, err
}
if c.cacheEnabled && resp.StatusCode >= 200 && resp.StatusCode <= 299 && req.Method == http.MethodGet {
c.Logger.Printf("[INFO] saving to cache, key:%s\n", key)
c.cache.Set(key, cache.CopyResponse(resp))
}
return resp, nil
}
// Request ... // Needs to review this function.
func (c *Client) GenericRequest(baseUrl, endpoint, method string, body io.Reader, urlParams url.Values, contentType string) ([]byte, error) {
if contentType == "" {
contentType = contentTypeJSON
}
var req *http.Request
var resp *http.Response
var err error
params := ""
if urlParams != nil {
params = urlParams.Encode()
}
if strings.Contains(endpoint, "?") && params != "" {
endpoint += "&" + params
} else if params != "" {
endpoint += "?" + params
}
fullURL := fmt.Sprintf("%s%s", baseUrl, endpoint)
isSandboxRequest := baseUrl == c.GetSandboxURL()
req, err = http.NewRequest(method, fullURL, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentType)
if c.UserAgent != "" {
req.Header.Add("User-Agent", c.UserAgent)
}
var otherHeaders map[string]string
if !isSandboxRequest {
err = c.checkSession()
if err != nil {
return nil, err
}
otherHeaders = map[string]string{"JSessionID": c.session.JSessionID}
}
reqID := uuid.New().String()
start := time.Now()
logger.LogRequest(c.Logger, req, reqID, otherHeaders, !isSandboxRequest)
for retry := 1; retry <= 5; retry++ {
if !isSandboxRequest {
err = c.checkSession()
if err != nil {
return nil, err
}
}
resp, err = c.do(req, start, reqID)
if err != nil {
return nil, err
}
if resp.StatusCode <= 299 {
defer resp.Body.Close()
break
}
resp.Body.Close()
if resp.StatusCode > 299 && resp.StatusCode != http.StatusUnauthorized {
return nil, checkErrorInResponse(resp, fmt.Errorf("api responded with code: %d", resp.StatusCode))
}
}
bodyResp, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bodyResp, nil
}
// Request ... // Needs to review this function.
func (c *Client) Request(endpoint, method string, data []byte, contentType string) ([]byte, error) {
return c.GenericRequest(c.URL, endpoint, method, bytes.NewReader(data), nil, contentType)
}
func (client *Client) WithFreshCache() {
client.freshCache = true
}
// Create send HTTP Post request.
func (c *Client) Create(endpoint string, o interface{}) (interface{}, error) {
if o == nil {
return nil, errors.New("tried to create with a nil payload not a Struct")
}
t := reflect.TypeOf(o)
if t.Kind() != reflect.Struct {
return nil, errors.New("tried to create with a " + t.Kind().String() + " not a Struct")
}
data, err := json.Marshal(o)
if err != nil {
return nil, err
}
resp, err := c.Request(endpoint, "POST", data, "application/json")
if err != nil {
return nil, err
}
if len(resp) > 0 {
responseObject := reflect.New(t).Interface()
err = json.Unmarshal(resp, &responseObject)
if err != nil {
return nil, err
}
id := reflect.Indirect(reflect.ValueOf(responseObject)).FieldByName("ID")
c.Logger.Printf("Created Object with ID %v", id)
return responseObject, nil
} else {
// in case of 204 no content
return nil, nil
}
}
// Read ...
func (c *Client) Read(endpoint string, o interface{}) error {
contentType := c.GetContentType()
resp, err := c.Request(endpoint, "GET", nil, contentType)
if err != nil {
return err
}
err = json.Unmarshal(resp, o)
if err != nil {
return err
}
return nil
}
// Update ...
func (c *Client) UpdateWithPut(endpoint string, o interface{}) (interface{}, error) {
return c.updateGeneric(endpoint, o, "PUT", "application/json")
}
// Update ...
func (c *Client) Update(endpoint string, o interface{}) (interface{}, error) {
return c.updateGeneric(endpoint, o, "PATCH", "application/merge-patch+json")
}
// Update ...
func (c *Client) updateGeneric(endpoint string, o interface{}, method, contentType string) (interface{}, error) {
if o == nil {
return nil, errors.New("tried to update with a nil payload not a Struct")
}
t := reflect.TypeOf(o)
if t.Kind() != reflect.Struct {
return nil, errors.New("tried to update with a " + t.Kind().String() + " not a Struct")
}
data, err := json.Marshal(o)
if err != nil {
return nil, err
}
resp, err := c.Request(endpoint, method, data, contentType)
if err != nil {
return nil, err
}
responseObject := reflect.New(t).Interface()
err = json.Unmarshal(resp, &responseObject)
return responseObject, err
}
// Delete ...
func (c *Client) Delete(endpoint string) error {
_, err := c.Request(endpoint, "DELETE", nil, "application/json")
if err != nil {
return err
}
return nil
}