-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathairvantage.go
236 lines (192 loc) · 6.25 KB
/
airvantage.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
227
228
229
230
231
232
233
234
235
236
package airvantage
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"golang.org/x/oauth2"
)
const (
defaultTimeout = 5 * time.Second
)
// AirVantage API client using oAuth2
type AirVantage struct {
client *http.Client
CompanyUID string
Debug bool
baseURLv1 *url.URL
baseURLv2 *url.URL
}
// NewClient logins to AirVantage an returns a new API client.
func NewClient(host, clientID, clientSecret, login, password string) (*AirVantage, error) {
scheme := "https"
if strings.HasPrefix(host, "http://") {
scheme = "http"
host = strings.TrimPrefix(host, "http://")
} else {
host = strings.TrimPrefix(host, "https://")
}
oauthURL := &url.URL{Host: host, Scheme: scheme, Path: "/api/oauth/"}
conf := &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Endpoint: oauth2.Endpoint{
TokenURL: oauthURL.ResolveReference(&url.URL{Path: "token"}).String(),
AuthURL: oauthURL.ResolveReference(&url.URL{Path: "auth"}).String(),
},
}
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, http.Client{Timeout: defaultTimeout})
slog.Info("Fetching OAuth token")
token, err := conf.PasswordCredentialsToken(ctx, login, password)
if err != nil {
return nil, err
}
return &AirVantage{
client: conf.Client(ctx, token),
baseURLv1: &url.URL{Host: host, Scheme: scheme, Path: "/api/v1/"},
baseURLv2: &url.URL{Host: host, Scheme: scheme, Path: "/api/v2/"},
},
nil
}
// get with smart URL formatting (API v1)
func (av *AirVantage) get(format string, a ...any) (*http.Response, error) {
return av.client.Get(av.URL(format, a...))
}
// get with smart URL formatting (API v2)
func (av *AirVantage) getV2(format string, a ...any) (*http.Response, error) {
return av.client.Get(av.URLv2(format, a...))
}
// get with query parameters (API v1)
func (av *AirVantage) getWithParams(path string, params url.Values) (*http.Response, error) {
copy := url.Values{}
for k := range params {
copy.Add(k, params.Get(k))
}
if av.CompanyUID != "" && !copy.Has("company") {
copy.Add("company", av.CompanyUID)
}
return av.client.Get(av.baseURLv1.ResolveReference(&url.URL{Path: path, RawQuery: copy.Encode()}).String())
}
type apiError struct {
Error string
ErrorParameters []string
}
// parseResponse is the standard way to handle HTTP responses from AirVantage.
// respStruct must be a pointer to a struct where the JSON will be deserialized.
func (av *AirVantage) parseResponse(resp *http.Response, respStruct any, maskedUrlParams ...string) error {
defer resp.Body.Close()
if err := av.parseError(resp); err != nil {
return err
}
if respStruct == nil {
return fmt.Errorf("parsing type not set")
}
var payload io.Reader = resp.Body
if av.Debug {
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
slog.Debug("Parsing response", "path", maskUrlParams(resp.Request.URL.String(), maskedUrlParams), "content", string(body))
payload = bytes.NewReader(body)
}
if err := json.NewDecoder(payload).Decode(respStruct); err != nil {
return fmt.Errorf("unable to parse API response: %s", err)
}
return nil
}
// parseResponseSerializedJava is similar to parseResponse
// but handle the response of serialized Java object (by removing references using regexp pattern)
// respStruct must be a pointer to a struct where the JSON will be deserialized.
func (av *AirVantage) parseResponseSerializedJava(resp *http.Response, respStruct any, pattern string, maskedUrlParams ...string) error {
defer resp.Body.Close()
if err := av.parseError(resp); err != nil {
return err
}
if respStruct == nil {
return fmt.Errorf("parsing type not set")
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
slog.Debug("Parsing serialized java response", "path", maskUrlParams(resp.Request.URL.String(), maskedUrlParams), "content", string(body))
// use a regexp to remove the Java object reference from the response
// it's much easier to do that rather than parsing json into a []any
reg := regexp.MustCompile(pattern)
jsonFiltered := reg.ReplaceAllString(string(body), "")
if err := json.Unmarshal([]byte(jsonFiltered), &respStruct); err != nil {
return fmt.Errorf("unable to parse API response: %s", err)
}
return nil
}
func (av *AirVantage) parseError(resp *http.Response) error {
if resp.StatusCode > 299 {
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
slog.Debug("Parsing error", "path", resp.Request.URL.String(), "content", string(body))
if len(body) == 0 {
return fmt.Errorf("error %d %s", resp.StatusCode, resp.Status)
}
apierror := apiError{}
if err = json.Unmarshal(body, &apierror); err != nil {
return fmt.Errorf("unable to parse API error: %s", err)
}
if apierror.Error != "" {
return avError(resp.Request.URL.Path, apierror.Error, apierror.ErrorParameters)
}
}
return nil
}
// SetTimeout sets the request timeout of the HTTP client.
func (av *AirVantage) SetTimeout(timeout time.Duration) {
av.client.Timeout = timeout
}
// URL builds a URL with the right host and prefix for API calls (API v1)
func (av *AirVantage) URL(path string, a ...any) string {
v := url.Values{}
if av.CompanyUID != "" {
v.Set("company", av.CompanyUID)
}
for i := 0; i < len(a); i += 2 {
if aStr, ok := a[i+1].(string); ok {
v.Add(a[i].(string), aStr)
} else {
v.Add(a[i].(string), fmt.Sprintf("%v", a[i+1]))
}
}
return av.baseURLv1.ResolveReference(&url.URL{Path: path, RawQuery: v.Encode()}).String()
}
// URLv2 builds a URL with the right host and prefix for API calls (api/v2 prefix)
func (av *AirVantage) URLv2(path string, a ...any) string {
v := url.Values{}
if av.CompanyUID != "" {
v.Set("company", av.CompanyUID)
}
for i := 0; i < len(a); i += 2 {
if aStr, ok := a[i+1].(string); ok {
v.Add(a[i].(string), aStr)
} else {
v.Add(a[i].(string), fmt.Sprintf("%v", a[i+1]))
}
}
return av.baseURLv2.ResolveReference(&url.URL{Path: path, RawQuery: v.Encode()}).String()
}
// mask the value of specified query string parameters
func maskUrlParams(url string, maskedParams []string) string {
for _, param := range maskedParams {
pattern := `([?&]` + param + `=)([^&]*)`
var re = regexp.MustCompile(pattern)
url = re.ReplaceAllString(url, "${1}***")
}
return url
}