github.com/vmware/go-vmware-nsxt@v0.0.0-20230223012718-d31b8a1ca05e/api_client.go (about) 1 /* Copyright © 2017 VMware, Inc. All Rights Reserved. 2 SPDX-License-Identifier: BSD-2-Clause 3 4 Generated by: https://github.com/swagger-api/swagger-codegen.git */ 5 6 package nsxt 7 8 import ( 9 "bytes" 10 "context" 11 "crypto/tls" 12 "crypto/x509" 13 "encoding/base64" 14 "encoding/json" 15 "encoding/xml" 16 "errors" 17 "fmt" 18 "golang.org/x/oauth2" 19 "io" 20 "io/ioutil" 21 "log" 22 "math" 23 "math/rand" 24 "mime/multipart" 25 "net/http" 26 "net/url" 27 "os" 28 "path/filepath" 29 "reflect" 30 "regexp" 31 "strconv" 32 "strings" 33 "time" 34 "unicode/utf8" 35 ) 36 37 var ( 38 jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") 39 xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") 40 ) 41 42 // APIClient manages communication with the NSX API API v1.0.0 43 // In most cases there should be only one, shared, APIClient. 44 type APIClient struct { 45 cfg *Configuration 46 Context context.Context 47 common service // Reuse a single struct instead of allocating one for each service on the heap. 48 49 // API Services 50 AaaApi *AaaApiService 51 AggregationServiceApi *AggregationServiceApiService 52 ApiServicesApi *ApiServicesApiService 53 AppDiscoveryApi *AppDiscoveryApiService 54 AssociationsApi *AssociationsApiService 55 CloudServiceManagerApi *CloudServiceManagerApiService 56 ErrorResolverApi *ErrorResolverApiService 57 FabricApi *FabricApiService 58 GroupingObjectsApi *GroupingObjectsApiService 59 LicensingApi *LicensingApiService 60 LogicalRoutingAndServicesApi *LogicalRoutingAndServicesApiService 61 LogicalSwitchingApi *LogicalSwitchingApiService 62 NetworkTransportApi *NetworkTransportApiService 63 NormalizationApi *NormalizationApiService 64 NsxComponentAdministrationApi *NsxComponentAdministrationApiService 65 NsxManagerHealthApi *NsxManagerHealthApiService 66 OperationsApi *OperationsApiService 67 PolicyApi *PolicyApiService 68 PoolManagementApi *PoolManagementApiService 69 RealizationApi *RealizationApiService 70 ServicesApi *ServicesApiService 71 SupportBundleApi *SupportBundleApiService 72 TransportEntitiesApi *TransportEntitiesApiService 73 TroubleshootingAndMonitoringApi *TroubleshootingAndMonitoringApiService 74 UpgradeApi *UpgradeApiService 75 ContainerApplicationsApi *ManagementPlaneApiFabricContainerApplicationsApiService 76 ContainerClustersApi *ManagementPlaneApiFabricContainerClustersApiService 77 ContainerInventoryApi *ManagementPlaneApiFabricContainerInventoryApiService 78 ContainerProjectsApi *ManagementPlaneApiFabricContainerProjectsApiService 79 ClusterControlPlaneApi *SystemAdministrationPolicyClusterControlPlaneApiService 80 } 81 82 type service struct { 83 client *APIClient 84 } 85 86 func GetContext(cfg *Configuration) context.Context { 87 if len(cfg.ClientAuthCertFile) == 0 && len(cfg.ClientAuthCertString) == 0 && cfg.RemoteAuth == false { 88 auth := BasicAuth{UserName: cfg.UserName, 89 Password: cfg.Password} 90 return context.WithValue(context.Background(), ContextBasicAuth, auth) 91 } 92 93 return context.Background() 94 } 95 96 //Perform 'session create' and save the xsrf & session id to the default headers 97 func GetDefaultHeaders(client *APIClient) error { 98 99 XSRF_TOKEN := "X-XSRF-TOKEN" 100 var ( 101 httpMethod = strings.ToUpper("Post") 102 fileName string 103 fileBytes []byte 104 ) 105 queryParams := url.Values{} 106 formParams := url.Values{} 107 108 requestHeaders := map[string]string{ 109 "Accept": "application/json", 110 "Content-Type": "application/x-www-form-urlencoded", 111 } 112 113 if client.cfg.DefaultHeader == nil { 114 client.cfg.DefaultHeader = make(map[string]string) 115 } 116 117 // For remote Auth (vIDM use case), construct the REMOTE auth header 118 remoteAuthHeader := "" 119 if client.cfg.RemoteAuth { 120 auth := client.cfg.UserName + ":" + client.cfg.Password 121 encoded := base64.StdEncoding.EncodeToString([]byte(auth)) 122 remoteAuthHeader = "Remote " + encoded 123 requestHeaders["Authorization"] = remoteAuthHeader 124 125 client.cfg.DefaultHeader["Authorization"] = remoteAuthHeader 126 } 127 128 postBody := fmt.Sprintf("j_username=%s&j_password=%s", client.cfg.UserName, client.cfg.Password) 129 path := strings.TrimSuffix(client.cfg.BasePath, "v1") + "session/create" 130 // Call session create 131 r, err := client.prepareRequest( 132 client.Context, 133 path, 134 httpMethod, 135 postBody, 136 requestHeaders, 137 queryParams, 138 formParams, 139 fileName, 140 fileBytes) 141 if err != nil { 142 return fmt.Errorf("Failed to create session: %s", err) 143 } 144 response, err := client.callAPI(r) 145 if err != nil || response == nil { 146 return fmt.Errorf("Failed to create session: %s", err) 147 } 148 149 if response.StatusCode != 200 { 150 return fmt.Errorf("Failed to create session: status code %d", response.StatusCode) 151 } 152 153 // Go over the headers 154 for k, v := range response.Header { 155 if strings.ToLower("Set-Cookie") == strings.ToLower(k) { 156 r, _ := regexp.Compile("JSESSIONID=.*?;") 157 result := r.FindString(v[0]) 158 if result != "" { 159 client.cfg.DefaultHeader["Cookie"] = result 160 } 161 } 162 if strings.ToLower(XSRF_TOKEN) == strings.ToLower(k) { 163 client.cfg.DefaultHeader[XSRF_TOKEN] = v[0] 164 } 165 } 166 167 response.Body.Close() 168 169 return nil 170 } 171 172 func InitHttpClient(cfg *Configuration) error { 173 174 tlsConfig := &tls.Config{ 175 //MinVersion: tls.VersionTLS12, 176 //PreferServerCipherSuites: true, 177 InsecureSkipVerify: cfg.Insecure, 178 } 179 180 if len(cfg.ClientAuthCertFile) > 0 { 181 cert, err := tls.LoadX509KeyPair(cfg.ClientAuthCertFile, 182 cfg.ClientAuthKeyFile) 183 if err != nil { 184 return err 185 } 186 187 tlsConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { 188 return &cert, nil 189 } 190 191 } 192 193 if len(cfg.ClientAuthCertString) > 0 { 194 cert, err := tls.X509KeyPair([]byte(cfg.ClientAuthCertString), 195 []byte(cfg.ClientAuthKeyString)) 196 if err != nil { 197 return err 198 } 199 200 tlsConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { 201 return &cert, nil 202 } 203 204 } 205 206 if len(cfg.CAFile) > 0 { 207 caCert, err := ioutil.ReadFile(cfg.CAFile) 208 if err != nil { 209 return err 210 } 211 212 caCertPool := x509.NewCertPool() 213 caCertPool.AppendCertsFromPEM(caCert) 214 215 tlsConfig.RootCAs = caCertPool 216 } 217 218 if len(cfg.CAString) > 0 { 219 220 caCertPool := x509.NewCertPool() 221 caCertPool.AppendCertsFromPEM([]byte(cfg.CAString)) 222 223 tlsConfig.RootCAs = caCertPool 224 } 225 226 transport := &http.Transport{Proxy: http.ProxyFromEnvironment, 227 TLSClientConfig: tlsConfig, 228 MaxIdleConns: 100, 229 MaxIdleConnsPerHost: 100, 230 } 231 cfg.HTTPClient = &http.Client{Transport: transport} 232 return nil 233 } 234 235 // NewAPIClient creates a new API client. Requires a userAgent string describing your application. 236 // optionally a custom http.Client to allow for advanced features such as caching. 237 func NewAPIClient(cfg *Configuration) (*APIClient, error) { 238 239 if cfg.HTTPClient == nil { 240 err := InitHttpClient(cfg) 241 242 if cfg.HTTPClient == nil { 243 return nil, err 244 } 245 } 246 247 c := &APIClient{} 248 c.cfg = cfg 249 c.Context = GetContext(cfg) 250 c.common.client = c 251 if !c.cfg.SkipSessionAuth { 252 err := GetDefaultHeaders(c) 253 if err != nil { 254 log.Printf("Warning: %v", err) 255 } 256 } 257 258 // API Services 259 c.AaaApi = (*AaaApiService)(&c.common) 260 c.AggregationServiceApi = (*AggregationServiceApiService)(&c.common) 261 c.ApiServicesApi = (*ApiServicesApiService)(&c.common) 262 c.AppDiscoveryApi = (*AppDiscoveryApiService)(&c.common) 263 c.AssociationsApi = (*AssociationsApiService)(&c.common) 264 c.CloudServiceManagerApi = (*CloudServiceManagerApiService)(&c.common) 265 c.ErrorResolverApi = (*ErrorResolverApiService)(&c.common) 266 c.FabricApi = (*FabricApiService)(&c.common) 267 c.GroupingObjectsApi = (*GroupingObjectsApiService)(&c.common) 268 c.LicensingApi = (*LicensingApiService)(&c.common) 269 c.LogicalRoutingAndServicesApi = (*LogicalRoutingAndServicesApiService)(&c.common) 270 c.LogicalSwitchingApi = (*LogicalSwitchingApiService)(&c.common) 271 c.NetworkTransportApi = (*NetworkTransportApiService)(&c.common) 272 c.NormalizationApi = (*NormalizationApiService)(&c.common) 273 c.NsxComponentAdministrationApi = (*NsxComponentAdministrationApiService)(&c.common) 274 c.NsxManagerHealthApi = (*NsxManagerHealthApiService)(&c.common) 275 c.OperationsApi = (*OperationsApiService)(&c.common) 276 c.PolicyApi = (*PolicyApiService)(&c.common) 277 c.PoolManagementApi = (*PoolManagementApiService)(&c.common) 278 c.RealizationApi = (*RealizationApiService)(&c.common) 279 c.ServicesApi = (*ServicesApiService)(&c.common) 280 c.SupportBundleApi = (*SupportBundleApiService)(&c.common) 281 c.TransportEntitiesApi = (*TransportEntitiesApiService)(&c.common) 282 c.TroubleshootingAndMonitoringApi = (*TroubleshootingAndMonitoringApiService)(&c.common) 283 c.UpgradeApi = (*UpgradeApiService)(&c.common) 284 c.ContainerApplicationsApi = (*ManagementPlaneApiFabricContainerApplicationsApiService)(&c.common) 285 c.ContainerClustersApi = (*ManagementPlaneApiFabricContainerClustersApiService)(&c.common) 286 c.ContainerInventoryApi = (*ManagementPlaneApiFabricContainerInventoryApiService)(&c.common) 287 c.ContainerProjectsApi = (*ManagementPlaneApiFabricContainerProjectsApiService)(&c.common) 288 c.ClusterControlPlaneApi = (*SystemAdministrationPolicyClusterControlPlaneApiService)(&c.common) 289 return c, nil 290 } 291 292 func atoi(in string) (int, error) { 293 return strconv.Atoi(in) 294 } 295 296 // selectHeaderContentType select a content type from the available list. 297 func selectHeaderContentType(contentTypes []string) string { 298 if len(contentTypes) == 0 { 299 return "" 300 } 301 if contains(contentTypes, "application/json") { 302 return "application/json" 303 } 304 return contentTypes[0] // use the first content type specified in 'consumes' 305 } 306 307 // selectHeaderAccept join all accept types and return 308 func selectHeaderAccept(accepts []string) string { 309 if len(accepts) == 0 { 310 return "" 311 } 312 313 if contains(accepts, "application/json") { 314 return "application/json" 315 } 316 317 return strings.Join(accepts, ",") 318 } 319 320 // contains is a case insenstive match, finding needle in a haystack 321 func contains(haystack []string, needle string) bool { 322 for _, a := range haystack { 323 if strings.ToLower(a) == strings.ToLower(needle) { 324 return true 325 } 326 } 327 return false 328 } 329 330 // Verify optional parameters are of the correct type. 331 func typeCheckParameter(obj interface{}, expected string, name string) error { 332 // Make sure there is an object. 333 if obj == nil { 334 return nil 335 } 336 337 // Check the type is as expected. 338 if reflect.TypeOf(obj).String() != expected { 339 return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) 340 } 341 return nil 342 } 343 344 // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. 345 func parameterToString(obj interface{}, collectionFormat string) string { 346 var delimiter string 347 348 switch collectionFormat { 349 case "pipes": 350 delimiter = "|" 351 case "ssv": 352 delimiter = " " 353 case "tsv": 354 delimiter = "\t" 355 case "csv": 356 delimiter = "," 357 } 358 359 if reflect.TypeOf(obj).Kind() == reflect.Slice { 360 return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") 361 } 362 363 return fmt.Sprintf("%v", obj) 364 } 365 366 func (c *APIClient) shouldRetryOnStatus(code int) bool { 367 for _, s := range c.cfg.RetriesConfiguration.RetryOnStatuses { 368 if code == s { 369 return true 370 } 371 } 372 return false 373 } 374 375 // callAPI do the request. 376 func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { 377 378 // keep the initial request body string 379 var requestBodyString string 380 if request.Body != nil { 381 buf := new(bytes.Buffer) 382 buf.ReadFrom(request.Body) 383 requestBodyString = buf.String() 384 request.Body = ioutil.NopCloser(strings.NewReader(requestBodyString)) 385 } 386 387 // first run 388 localVarHttpResponse, err := c.callAPIInternal(request) 389 config := c.cfg.RetriesConfiguration 390 maxRetries := int(math.Max(2, float64(config.MaxRetries))) 391 // loop until not getting the retry-able error, or until max retries 392 for n_try := 1; n_try < maxRetries; n_try++ { 393 if localVarHttpResponse == nil || c.shouldRetryOnStatus(localVarHttpResponse.StatusCode) { 394 status := 0 395 if localVarHttpResponse != nil { 396 status = localVarHttpResponse.StatusCode 397 localVarHttpResponse.Body.Close() 398 } 399 log.Printf("[DEBUG] Retrying request %s %s for the %d time because of status %d", request.Method, request.URL, n_try, status) 400 // sleep a random increasing time 401 minDelay := 1 402 if config.RetryMinDelay > 0 { 403 minDelay = config.RetryMinDelay 404 } 405 float_delay := float64(rand.Intn(minDelay * n_try)) 406 fixed_delay := time.Duration(math.Min(float64(config.RetryMaxDelay), float_delay)) 407 time.Sleep(fixed_delay * time.Millisecond) 408 // reset Request.Body 409 if request.Body != nil { 410 request.Body = ioutil.NopCloser(strings.NewReader(requestBodyString)) 411 } 412 // perform the request again 413 localVarHttpResponse, err = c.callAPIInternal(request) 414 } else { 415 // Non retry-able response 416 return localVarHttpResponse, err 417 } 418 } 419 // max retries exceeded 420 return localVarHttpResponse, err 421 } 422 423 func (c *APIClient) callAPIInternal(request *http.Request) (*http.Response, error) { 424 localVarHttpResponse, err := c.cfg.HTTPClient.Do(request) 425 426 if err == nil && localVarHttpResponse != nil && (localVarHttpResponse.StatusCode == 400 || localVarHttpResponse.StatusCode == 500) { 427 bodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body) 428 err = reportError("Status: %v, Body: %s", localVarHttpResponse.Status, bodyBytes) 429 } 430 431 return localVarHttpResponse, err 432 } 433 434 // Change base path to allow switching to mocks 435 func (c *APIClient) ChangeBasePath(path string) { 436 c.cfg.BasePath = path 437 } 438 439 // prepareRequest build the request 440 func (c *APIClient) prepareRequest( 441 ctx context.Context, 442 path string, method string, 443 postBody interface{}, 444 headerParams map[string]string, 445 queryParams url.Values, 446 formParams url.Values, 447 fileName string, 448 fileBytes []byte) (localVarRequest *http.Request, err error) { 449 450 var body *bytes.Buffer 451 452 // Detect postBody type and post. 453 if postBody != nil { 454 contentType := headerParams["Content-Type"] 455 if contentType == "" { 456 contentType = detectContentType(postBody) 457 headerParams["Content-Type"] = contentType 458 } 459 460 body, err = setBody(postBody, contentType) 461 if err != nil { 462 return nil, err 463 } 464 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 465 } 466 467 // add form paramters and file if available. 468 if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { 469 if body != nil { 470 return nil, errors.New("Cannot specify postBody and multipart form at the same time.") 471 } 472 body = &bytes.Buffer{} 473 w := multipart.NewWriter(body) 474 475 for k, v := range formParams { 476 for _, iv := range v { 477 if strings.HasPrefix(k, "@") { // file 478 err = addFile(w, k[1:], iv) 479 if err != nil { 480 return nil, err 481 } 482 } else { // form value 483 w.WriteField(k, iv) 484 } 485 } 486 } 487 if len(fileBytes) > 0 && fileName != "" { 488 w.Boundary() 489 //_, fileNm := filepath.Split(fileName) 490 part, err := w.CreateFormFile("file", filepath.Base(fileName)) 491 if err != nil { 492 return nil, err 493 } 494 _, err = part.Write(fileBytes) 495 if err != nil { 496 return nil, err 497 } 498 // Set the Boundary in the Content-Type 499 headerParams["Content-Type"] = w.FormDataContentType() 500 } 501 502 // Set Content-Length 503 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 504 w.Close() 505 } 506 507 // Setup path and query paramters 508 url, err := url.Parse(path) 509 if err != nil { 510 return nil, err 511 } 512 513 // Adding Query Param 514 query := url.Query() 515 for k, v := range queryParams { 516 for _, iv := range v { 517 query.Add(k, iv) 518 } 519 } 520 521 // Encode the parameters. 522 url.RawQuery = query.Encode() 523 524 // Generate a new request 525 if body != nil { 526 localVarRequest, err = http.NewRequest(method, url.String(), body) 527 } else { 528 localVarRequest, err = http.NewRequest(method, url.String(), nil) 529 } 530 if err != nil { 531 return nil, err 532 } 533 534 // add header parameters, if any 535 if len(headerParams) > 0 { 536 headers := http.Header{} 537 for h, v := range headerParams { 538 headers.Set(h, v) 539 } 540 localVarRequest.Header = headers 541 } 542 543 // Override request host, if applicable 544 if c.cfg.Host != "" { 545 localVarRequest.URL.Host = c.cfg.Host 546 } 547 548 if c.cfg.Scheme != "" { 549 localVarRequest.URL.Scheme = c.cfg.Scheme 550 } 551 552 // Add the user agent to the request. 553 localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) 554 555 // Walk through any authentication. 556 if ctx != nil { 557 // OAuth2 authentication 558 if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { 559 // We were able to grab an oauth2 token from the context 560 var latestToken *oauth2.Token 561 if latestToken, err = tok.Token(); err != nil { 562 return nil, err 563 } 564 565 latestToken.SetAuthHeader(localVarRequest) 566 } 567 568 // Basic HTTP Authentication 569 if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { 570 localVarRequest.SetBasicAuth(auth.UserName, auth.Password) 571 } 572 573 // AccessToken Authentication 574 if auth, ok := ctx.Value(ContextAccessToken).(string); ok { 575 localVarRequest.Header.Add("Authorization", "Bearer "+auth) 576 } 577 } 578 579 for header, value := range c.cfg.DefaultHeader { 580 localVarRequest.Header.Add(header, value) 581 } 582 583 return localVarRequest, nil 584 } 585 586 // Add a file to the multipart request 587 func addFile(w *multipart.Writer, fieldName, path string) error { 588 file, err := os.Open(path) 589 if err != nil { 590 return err 591 } 592 defer file.Close() 593 594 part, err := w.CreateFormFile(fieldName, filepath.Base(path)) 595 if err != nil { 596 return err 597 } 598 _, err = io.Copy(part, file) 599 600 return err 601 } 602 603 // Prevent trying to import "fmt" 604 func reportError(format string, a ...interface{}) error { 605 return fmt.Errorf(format, a...) 606 } 607 608 // Set request body from an interface{} 609 func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { 610 if bodyBuf == nil { 611 bodyBuf = &bytes.Buffer{} 612 } 613 614 if reader, ok := body.(io.Reader); ok { 615 _, err = bodyBuf.ReadFrom(reader) 616 } else if b, ok := body.([]byte); ok { 617 _, err = bodyBuf.Write(b) 618 } else if s, ok := body.(string); ok { 619 _, err = bodyBuf.WriteString(s) 620 } else if jsonCheck.MatchString(contentType) { 621 err = json.NewEncoder(bodyBuf).Encode(body) 622 } else if xmlCheck.MatchString(contentType) { 623 xml.NewEncoder(bodyBuf).Encode(body) 624 } 625 626 if err != nil { 627 return nil, err 628 } 629 630 if bodyBuf.Len() == 0 { 631 err = fmt.Errorf("Invalid body type %s\n", contentType) 632 return nil, err 633 } 634 return bodyBuf, nil 635 } 636 637 // detectContentType method is used to figure out `Request.Body` content type for request header 638 func detectContentType(body interface{}) string { 639 contentType := "text/plain; charset=utf-8" 640 kind := reflect.TypeOf(body).Kind() 641 642 switch kind { 643 case reflect.Struct, reflect.Map, reflect.Ptr: 644 contentType = "application/json; charset=utf-8" 645 case reflect.String: 646 contentType = "text/plain; charset=utf-8" 647 default: 648 if b, ok := body.([]byte); ok { 649 contentType = http.DetectContentType(b) 650 } else if kind == reflect.Slice { 651 contentType = "application/json; charset=utf-8" 652 } 653 } 654 655 return contentType 656 } 657 658 // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go 659 type cacheControl map[string]string 660 661 func parseCacheControl(headers http.Header) cacheControl { 662 cc := cacheControl{} 663 ccHeader := headers.Get("Cache-Control") 664 for _, part := range strings.Split(ccHeader, ",") { 665 part = strings.Trim(part, " ") 666 if part == "" { 667 continue 668 } 669 if strings.ContainsRune(part, '=') { 670 keyval := strings.Split(part, "=") 671 cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") 672 } else { 673 cc[part] = "" 674 } 675 } 676 return cc 677 } 678 679 // CacheExpires helper function to determine remaining time before repeating a request. 680 func CacheExpires(r *http.Response) time.Time { 681 // Figure out when the cache expires. 682 var expires time.Time 683 now, err := time.Parse(time.RFC1123, r.Header.Get("date")) 684 if err != nil { 685 return time.Now() 686 } 687 respCacheControl := parseCacheControl(r.Header) 688 689 if maxAge, ok := respCacheControl["max-age"]; ok { 690 lifetime, err := time.ParseDuration(maxAge + "s") 691 if err != nil { 692 expires = now 693 } 694 expires = now.Add(lifetime) 695 } else { 696 expiresHeader := r.Header.Get("Expires") 697 if expiresHeader != "" { 698 expires, err = time.Parse(time.RFC1123, expiresHeader) 699 if err != nil { 700 expires = now 701 } 702 } 703 } 704 return expires 705 } 706 707 func strlen(s string) int { 708 return utf8.RuneCountInString(s) 709 } 710 711 // Added for supporting NSX 3.0 Container Inventory API 712 func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { 713 if strings.Contains(contentType, "application/xml") { 714 if err = xml.Unmarshal(b, v); err != nil { 715 return err 716 } 717 return nil 718 } else if strings.Contains(contentType, "application/json") { 719 if err = json.Unmarshal(b, v); err != nil { 720 return err 721 } 722 return nil 723 } 724 return errors.New("undefined response type") 725 } 726 727 // GenericSwaggerError Provides access to the body, error and model on returned errors. 728 type GenericSwaggerError struct { 729 body []byte 730 error string 731 model interface{} 732 } 733 734 // Error returns non-empty string if there was an error. 735 func (e GenericSwaggerError) Error() string { 736 return e.error 737 } 738 739 // Body returns the raw bytes of the response 740 func (e GenericSwaggerError) Body() []byte { 741 return e.body 742 } 743 744 // Model returns the unpacked model of the error 745 func (e GenericSwaggerError) Model() interface{} { 746 return e.model 747 }