github.com/launchdarkly/api-client-go@v5.3.0+incompatible/client.go (about) 1 /* 2 * LaunchDarkly REST API 3 * 4 * Build custom integrations with the LaunchDarkly REST API 5 * 6 * API version: 5.3.0 7 * Contact: support@launchdarkly.com 8 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) 9 */ 10 11 package ldapi 12 13 import ( 14 "bytes" 15 "context" 16 "encoding/json" 17 "encoding/xml" 18 "errors" 19 "fmt" 20 "io" 21 "mime/multipart" 22 "net/http" 23 "net/url" 24 "os" 25 "path/filepath" 26 "reflect" 27 "regexp" 28 "strconv" 29 "strings" 30 "time" 31 "unicode/utf8" 32 33 "golang.org/x/oauth2" 34 ) 35 36 var ( 37 jsonCheck = regexp.MustCompile("(?i:(?:application|text)/json)") 38 xmlCheck = regexp.MustCompile("(?i:(?:application|text)/xml)") 39 ) 40 41 // APIClient manages communication with the LaunchDarkly REST API API v5.3.0 42 // In most cases there should be only one, shared, APIClient. 43 type APIClient struct { 44 cfg *Configuration 45 common service // Reuse a single struct instead of allocating one for each service on the heap. 46 47 // API Services 48 49 AccessTokensApi *AccessTokensApiService 50 51 AuditLogApi *AuditLogApiService 52 53 CustomRolesApi *CustomRolesApiService 54 55 CustomerMetricsApi *CustomerMetricsApiService 56 57 DataExportDestinationsApi *DataExportDestinationsApiService 58 59 EnvironmentsApi *EnvironmentsApiService 60 61 FeatureFlagsApi *FeatureFlagsApiService 62 63 IntegrationsApi *IntegrationsApiService 64 65 ProjectsApi *ProjectsApiService 66 67 RelayProxyConfigurationsApi *RelayProxyConfigurationsApiService 68 69 RootApi *RootApiService 70 71 TeamMembersApi *TeamMembersApiService 72 73 UserSegmentsApi *UserSegmentsApiService 74 75 UserSettingsApi *UserSettingsApiService 76 77 UsersApi *UsersApiService 78 79 WebhooksApi *WebhooksApiService 80 } 81 82 type service struct { 83 client *APIClient 84 } 85 86 // NewAPIClient creates a new API client. Requires a userAgent string describing your application. 87 // optionally a custom http.Client to allow for advanced features such as caching. 88 func NewAPIClient(cfg *Configuration) *APIClient { 89 if cfg.HTTPClient == nil { 90 cfg.HTTPClient = http.DefaultClient 91 } 92 93 c := &APIClient{} 94 c.cfg = cfg 95 c.common.client = c 96 97 // API Services 98 c.AccessTokensApi = (*AccessTokensApiService)(&c.common) 99 c.AuditLogApi = (*AuditLogApiService)(&c.common) 100 c.CustomRolesApi = (*CustomRolesApiService)(&c.common) 101 c.CustomerMetricsApi = (*CustomerMetricsApiService)(&c.common) 102 c.DataExportDestinationsApi = (*DataExportDestinationsApiService)(&c.common) 103 c.EnvironmentsApi = (*EnvironmentsApiService)(&c.common) 104 c.FeatureFlagsApi = (*FeatureFlagsApiService)(&c.common) 105 c.IntegrationsApi = (*IntegrationsApiService)(&c.common) 106 c.ProjectsApi = (*ProjectsApiService)(&c.common) 107 c.RelayProxyConfigurationsApi = (*RelayProxyConfigurationsApiService)(&c.common) 108 c.RootApi = (*RootApiService)(&c.common) 109 c.TeamMembersApi = (*TeamMembersApiService)(&c.common) 110 c.UserSegmentsApi = (*UserSegmentsApiService)(&c.common) 111 c.UserSettingsApi = (*UserSettingsApiService)(&c.common) 112 c.UsersApi = (*UsersApiService)(&c.common) 113 c.WebhooksApi = (*WebhooksApiService)(&c.common) 114 115 return c 116 } 117 118 func atoi(in string) (int, error) { 119 return strconv.Atoi(in) 120 } 121 122 // selectHeaderContentType select a content type from the available list. 123 func selectHeaderContentType(contentTypes []string) string { 124 if len(contentTypes) == 0 { 125 return "" 126 } 127 if contains(contentTypes, "application/json") { 128 return "application/json" 129 } 130 return contentTypes[0] // use the first content type specified in 'consumes' 131 } 132 133 // selectHeaderAccept join all accept types and return 134 func selectHeaderAccept(accepts []string) string { 135 if len(accepts) == 0 { 136 return "" 137 } 138 139 if contains(accepts, "application/json") { 140 return "application/json" 141 } 142 143 return strings.Join(accepts, ",") 144 } 145 146 // contains is a case insenstive match, finding needle in a haystack 147 func contains(haystack []string, needle string) bool { 148 for _, a := range haystack { 149 if strings.ToLower(a) == strings.ToLower(needle) { 150 return true 151 } 152 } 153 return false 154 } 155 156 // Verify optional parameters are of the correct type. 157 func typeCheckParameter(obj interface{}, expected string, name string) error { 158 // Make sure there is an object. 159 if obj == nil { 160 return nil 161 } 162 163 // Check the type is as expected. 164 if reflect.TypeOf(obj).String() != expected { 165 return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) 166 } 167 return nil 168 } 169 170 // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. 171 func parameterToString(obj interface{}, collectionFormat string) string { 172 var delimiter string 173 174 switch collectionFormat { 175 case "pipes": 176 delimiter = "|" 177 case "ssv": 178 delimiter = " " 179 case "tsv": 180 delimiter = "\t" 181 case "csv": 182 delimiter = "," 183 } 184 185 if reflect.TypeOf(obj).Kind() == reflect.Slice { 186 return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") 187 } 188 189 return fmt.Sprintf("%v", obj) 190 } 191 192 // callAPI do the request. 193 func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { 194 return c.cfg.HTTPClient.Do(request) 195 } 196 197 // Change base path to allow switching to mocks 198 func (c *APIClient) ChangeBasePath(path string) { 199 c.cfg.BasePath = path 200 } 201 202 // prepareRequest build the request 203 func (c *APIClient) prepareRequest( 204 ctx context.Context, 205 path string, method string, 206 postBody interface{}, 207 headerParams map[string]string, 208 queryParams url.Values, 209 formParams url.Values, 210 fileName string, 211 fileBytes []byte) (localVarRequest *http.Request, err error) { 212 213 var body *bytes.Buffer 214 215 // Detect postBody type and post. 216 if postBody != nil { 217 contentType := headerParams["Content-Type"] 218 if contentType == "" { 219 contentType = detectContentType(postBody) 220 headerParams["Content-Type"] = contentType 221 } 222 223 body, err = setBody(postBody, contentType) 224 if err != nil { 225 return nil, err 226 } 227 } 228 229 // add form parameters and file if available. 230 if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { 231 if body != nil { 232 return nil, errors.New("Cannot specify postBody and multipart form at the same time.") 233 } 234 body = &bytes.Buffer{} 235 w := multipart.NewWriter(body) 236 237 for k, v := range formParams { 238 for _, iv := range v { 239 if strings.HasPrefix(k, "@") { // file 240 err = addFile(w, k[1:], iv) 241 if err != nil { 242 return nil, err 243 } 244 } else { // form value 245 w.WriteField(k, iv) 246 } 247 } 248 } 249 if len(fileBytes) > 0 && fileName != "" { 250 w.Boundary() 251 //_, fileNm := filepath.Split(fileName) 252 part, err := w.CreateFormFile("file", filepath.Base(fileName)) 253 if err != nil { 254 return nil, err 255 } 256 _, err = part.Write(fileBytes) 257 if err != nil { 258 return nil, err 259 } 260 // Set the Boundary in the Content-Type 261 headerParams["Content-Type"] = w.FormDataContentType() 262 } 263 264 // Set Content-Length 265 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 266 w.Close() 267 } 268 269 if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { 270 if body != nil { 271 return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") 272 } 273 body = &bytes.Buffer{} 274 body.WriteString(formParams.Encode()) 275 // Set Content-Length 276 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 277 } 278 279 // Setup path and query parameters 280 url, err := url.Parse(path) 281 if err != nil { 282 return nil, err 283 } 284 285 // Adding Query Param 286 query := url.Query() 287 for k, v := range queryParams { 288 for _, iv := range v { 289 query.Add(k, iv) 290 } 291 } 292 293 // Encode the parameters. 294 url.RawQuery = query.Encode() 295 296 // Generate a new request 297 if body != nil { 298 localVarRequest, err = http.NewRequest(method, url.String(), body) 299 } else { 300 localVarRequest, err = http.NewRequest(method, url.String(), nil) 301 } 302 if err != nil { 303 return nil, err 304 } 305 306 // add header parameters, if any 307 if len(headerParams) > 0 { 308 headers := http.Header{} 309 for h, v := range headerParams { 310 headers.Set(h, v) 311 } 312 localVarRequest.Header = headers 313 } 314 315 // Override request host, if applicable 316 if c.cfg.Host != "" { 317 localVarRequest.Host = c.cfg.Host 318 } 319 320 // Add the user agent to the request. 321 localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) 322 323 if ctx != nil { 324 // add context to the request 325 localVarRequest = localVarRequest.WithContext(ctx) 326 327 // Walk through any authentication. 328 329 // OAuth2 authentication 330 if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { 331 // We were able to grab an oauth2 token from the context 332 var latestToken *oauth2.Token 333 if latestToken, err = tok.Token(); err != nil { 334 return nil, err 335 } 336 337 latestToken.SetAuthHeader(localVarRequest) 338 } 339 340 // Basic HTTP Authentication 341 if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { 342 localVarRequest.SetBasicAuth(auth.UserName, auth.Password) 343 } 344 345 // AccessToken Authentication 346 if auth, ok := ctx.Value(ContextAccessToken).(string); ok { 347 localVarRequest.Header.Add("Authorization", "Bearer "+auth) 348 } 349 } 350 351 for header, value := range c.cfg.DefaultHeader { 352 localVarRequest.Header.Add(header, value) 353 } 354 355 return localVarRequest, nil 356 } 357 358 func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { 359 if strings.Contains(contentType, "application/xml") { 360 if err = xml.Unmarshal(b, v); err != nil { 361 return err 362 } 363 return nil 364 } else if strings.Contains(contentType, "application/json") { 365 if err = json.Unmarshal(b, v); err != nil { 366 return err 367 } 368 return nil 369 } 370 return errors.New("undefined response type") 371 } 372 373 // Add a file to the multipart request 374 func addFile(w *multipart.Writer, fieldName, path string) error { 375 file, err := os.Open(path) 376 if err != nil { 377 return err 378 } 379 defer file.Close() 380 381 part, err := w.CreateFormFile(fieldName, filepath.Base(path)) 382 if err != nil { 383 return err 384 } 385 _, err = io.Copy(part, file) 386 387 return err 388 } 389 390 // Prevent trying to import "fmt" 391 func reportError(format string, a ...interface{}) error { 392 return fmt.Errorf(format, a...) 393 } 394 395 // Set request body from an interface{} 396 func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { 397 if bodyBuf == nil { 398 bodyBuf = &bytes.Buffer{} 399 } 400 401 if reader, ok := body.(io.Reader); ok { 402 _, err = bodyBuf.ReadFrom(reader) 403 } else if b, ok := body.([]byte); ok { 404 _, err = bodyBuf.Write(b) 405 } else if s, ok := body.(string); ok { 406 _, err = bodyBuf.WriteString(s) 407 } else if s, ok := body.(*string); ok { 408 _, err = bodyBuf.WriteString(*s) 409 } else if jsonCheck.MatchString(contentType) { 410 err = json.NewEncoder(bodyBuf).Encode(body) 411 } else if xmlCheck.MatchString(contentType) { 412 xml.NewEncoder(bodyBuf).Encode(body) 413 } 414 415 if err != nil { 416 return nil, err 417 } 418 419 if bodyBuf.Len() == 0 { 420 err = fmt.Errorf("Invalid body type %s\n", contentType) 421 return nil, err 422 } 423 return bodyBuf, nil 424 } 425 426 // detectContentType method is used to figure out `Request.Body` content type for request header 427 func detectContentType(body interface{}) string { 428 contentType := "text/plain; charset=utf-8" 429 kind := reflect.TypeOf(body).Kind() 430 431 switch kind { 432 case reflect.Struct, reflect.Map, reflect.Ptr: 433 contentType = "application/json; charset=utf-8" 434 case reflect.String: 435 contentType = "text/plain; charset=utf-8" 436 default: 437 if b, ok := body.([]byte); ok { 438 contentType = http.DetectContentType(b) 439 } else if kind == reflect.Slice { 440 contentType = "application/json; charset=utf-8" 441 } 442 } 443 444 return contentType 445 } 446 447 // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go 448 type cacheControl map[string]string 449 450 func parseCacheControl(headers http.Header) cacheControl { 451 cc := cacheControl{} 452 ccHeader := headers.Get("Cache-Control") 453 for _, part := range strings.Split(ccHeader, ",") { 454 part = strings.Trim(part, " ") 455 if part == "" { 456 continue 457 } 458 if strings.ContainsRune(part, '=') { 459 keyval := strings.Split(part, "=") 460 cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") 461 } else { 462 cc[part] = "" 463 } 464 } 465 return cc 466 } 467 468 // CacheExpires helper function to determine remaining time before repeating a request. 469 func CacheExpires(r *http.Response) time.Time { 470 // Figure out when the cache expires. 471 var expires time.Time 472 now, err := time.Parse(time.RFC1123, r.Header.Get("date")) 473 if err != nil { 474 return time.Now() 475 } 476 respCacheControl := parseCacheControl(r.Header) 477 478 if maxAge, ok := respCacheControl["max-age"]; ok { 479 lifetime, err := time.ParseDuration(maxAge + "s") 480 if err != nil { 481 expires = now 482 } 483 expires = now.Add(lifetime) 484 } else { 485 expiresHeader := r.Header.Get("Expires") 486 if expiresHeader != "" { 487 expires, err = time.Parse(time.RFC1123, expiresHeader) 488 if err != nil { 489 expires = now 490 } 491 } 492 } 493 return expires 494 } 495 496 func strlen(s string) int { 497 return utf8.RuneCountInString(s) 498 } 499 500 // GenericSwaggerError Provides access to the body, error and model on returned errors. 501 type GenericSwaggerError struct { 502 body []byte 503 error string 504 model interface{} 505 } 506 507 // Error returns non-empty string if there was an error. 508 func (e GenericSwaggerError) Error() string { 509 return e.error 510 } 511 512 // Body returns the raw bytes of the response 513 func (e GenericSwaggerError) Body() []byte { 514 return e.body 515 } 516 517 // Model returns the unpacked model of the error 518 func (e GenericSwaggerError) Model() interface{} { 519 return e.model 520 }