### Complete NuSights Client Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/nusights-api.md A complete example demonstrating how to initialize the NuSights client, get current configuration, and update configuration. ```go package main import ( "context" "log" "github.com/go-openapi/strfmt" "github.com/nutanix-cloud-native/prism-go-client/nusights/client" ) func main() { ctx := context.Background() // Create client with custom configuration cfg := client.DefaultTransportConfig(). WithHost("insights.production.internal"). WithSchemes([]string{"https"}) httpClient := client.NewHTTPClientWithConfig(strfmt.Default, cfg) // Get current configuration config, err := httpClient.Config.GetConfigData(ctx) if err != nil { log.Fatalf("Failed to get config: %v", err) } log.Printf("Current Config Version: %s", config.ApiVersion) // Update configuration updateReq := &client.ConfigDataRequest{ Data: map[string]interface{}{ "retention_days": 90, "sampling_rate": 0.1, }, Merge: true, } updated, err := httpClient.Config.PutConfigData(ctx, updateReq) if err != nil { log.Fatalf("Failed to update config: %v", err) } log.Printf("Updated Config Version: %s", updated.ApiVersion) } ``` -------------------------------- ### Creator Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example of creating a new VM. ```go newVM := &VM{Name: "web-app"} created, err := client.VMs.Create(ctx, newVM) ``` -------------------------------- ### Credentials Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/types.md An example of how to initialize and populate the Credentials struct. ```go creds := Credentials{ Endpoint: "prism.internal", Username: "admin", Password: "password", Insecure: false, } ``` -------------------------------- ### NewV4Client Initialization Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example of initializing a V4 client with credentials and a read timeout option. ```go client, err := v4.NewV4Client(creds, v4.WithReadTimeout(30)) if err != nil { log.Println("Initialization failed:", err) } ``` -------------------------------- ### AsyncCreator Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example of creating a VM asynchronously and waiting for its completion. ```go op, err := client.VMs.CreateAsync(ctx, newVM) if err != nil { log.Fatal(err) } // Wait for completion results, err := op.Wait(ctx) if err != nil { log.Fatal(err) } log.Printf("Created VM: %v", results[0]) ``` -------------------------------- ### URL Building Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/internal-client.md Demonstrates how paths are constructed and provides an example of setting BaseURL and AbsolutePath. ```go client, _ := internal.NewClient( internal.WithBaseURL("prism.example.com"), internal.WithAbsolutePath("api/nutanix/v3"), ) // Get("/vms/uuid") → https://prism.example.com/api/nutanix/v3/vms/uuid ``` -------------------------------- ### DomainManagerService Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example usage of the DomainManagerService to get the Prism Central version. ```go // Get Prism Central version version, err := client.DomainManager.GetPrismCentralVersion(ctx) // Returns: "2023.4.0.1" or similar ``` -------------------------------- ### GenerateConsoleToken Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example of generating a console token for a VM. ```go token, err := client.VMs.GenerateConsoleToken(ctx, vmUUID) // Connect to: ws://prism-central/token.WsUri ``` -------------------------------- ### Certificate Verification Example (Production) Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example demonstrating how to configure credentials for production use with SSL certificate verification enabled. ```go credentials := prismgoclient.Credentials{ Endpoint: "prism.example.com", Username: "admin", Password: "password", Insecure: false, // Verify certificates } ``` -------------------------------- ### TasksService Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example usage of the TasksService to get a task, get a task with specific fields, and cancel a task. ```go task, err := client.Tasks.Get(ctx, taskUUID) // Get task with specific fields task, _ := client.Tasks.GetWithSelect(ctx, taskUUID, []string{"uuid", "status"}) // Cancel task msg, _ := client.Tasks.Cancel(ctx, taskUUID) ``` -------------------------------- ### NewClient Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example demonstrating how to initialize a v4 converged client and use it to list VMs. ```go credentials := prismgoclient.Credentials{ Endpoint: "prism-central.example.com", Username: "admin", Password: "password123", } client, err := v4.NewClient(credentials) if err != nil { log.Fatal(err) } // Use client vms, err := client.VMs.List(ctx) ``` -------------------------------- ### Provisioning a VM Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md An example of provisioning a VM using the async creation method. ```go // See: converged-api.md → VMs[VM] → AsyncCreator[VM] vmSpec := &vmmModels.Vm{...} op, _ := client.VMs.CreateAsync(ctx, vmSpec) results, _ := op.Wait(ctx) log.Printf("Created VM: %s", results[0].Spec.Name) ``` -------------------------------- ### Getter Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example of retrieving a cluster by UUID. ```go cluster, err := client.Clusters.Get(ctx, "cluster-uuid") if err != nil { log.Fatal(err) } ``` -------------------------------- ### NewClient Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/internal-client.md Example of initializing a new internal HTTP client with credentials, user agent, and base URL. ```go import "github.com/nutanix-cloud-native/prism-go-client/internal" client, err := internal.NewClient( internal.WithCredentials(&creds), internal.WithUserAgent("my-app/1.0"), internal.WithBaseURL("https://prism.example.com"), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### WithSelect Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example of selecting specific fields to return. ```go vms, err := client.VMs.List(ctx, WithSelect("uuid,name,state")) ``` -------------------------------- ### NewV3Client Initialization Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/v3-api.md Example demonstrating how to initialize the V3 client using basic authentication and then use it to list VMs. ```go creds := prismgoclient.Credentials{ Endpoint: "prism-central.example.com", Username: "admin", Password: "password123", } v3Client, err := v3.NewV3Client(creds) if err != nil { log.Fatal(err) } // Use the V3 service vms, err := v3Client.V3.ListVM(ctx, nil) ``` -------------------------------- ### Service Error Example: Get Cluster Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example demonstrating error handling for fetching a cluster, specifically checking for a missing UUID. ```go cluster, err := client.Clusters.Get(ctx, "") if err != nil { // Error: "uuid is required" } ``` -------------------------------- ### WithOrderBy Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example of setting the ordering of results. ```go vms, err := client.VMs.List(ctx, WithOrderBy("name asc")) ``` -------------------------------- ### WithPage Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example of setting the page number for pagination. ```go vms, err := client.VMs.List(ctx, WithPage(2), WithLimit(20)) ``` -------------------------------- ### NewClientFromV4SDKClient Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example demonstrating how to create a converged client by wrapping an existing V4 SDK client. ```go sdkClient, _ := v4prismGoClient.NewV4Client(creds) convergedClient := v4.NewClientFromV4SDKClient(sdkClient) ``` -------------------------------- ### ImagesService Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example usage of the ImagesService for uploading and downloading images. ```go // Upload image err := client.Images.Upload(ctx, imageUUID, "/path/to/image.iso") // Download image fileDetail, _ := client.Images.GetFile(ctx, imageUUID) ``` -------------------------------- ### Cache Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example demonstrating how to use the cache to retrieve or store an entity. ```go cache := v4.NewCache() if cached, ok := cache.Get("cluster-" + clusterID); ok { return cached, nil } cluster, _ := client.Clusters.Get(ctx, clusterID) cache.Set("cluster-"+clusterID, cluster) ``` -------------------------------- ### VM Operations Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/v3-api.md Examples demonstrating how to use VM operations like CreateVM, ListVM, and ListAllVM. ```go // Create VM vmInput := &v3.VMIntentInput{ Spec: &v3.Vm{Name: "web-1"}, } resp, err := v3Client.V3.CreateVM(ctx, vmInput) // List with metadata meta := &v3.DSMetadata{ Length: ptr.To(20), Offset: ptr.To(0), } vms, _ := v3Client.V3.ListVM(ctx, meta) // List all with filter allVMs, _ := v3Client.V3.ListAllVM(ctx, "name==web*") ``` -------------------------------- ### WithCredentials Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/internal-client.md Example of using WithCredentials to configure a client with specific authentication details. ```go creds := &prismgoclient.Credentials{ Username: "admin", Password: "password", Endpoint: "prism.example.com", Insecure: false, ProxyURL: "http://proxy.internal:8080", } client, _ := internal.NewClient(internal.WithCredentials(creds)) ``` -------------------------------- ### VMsService Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example usage of the VMsService for asynchronous VM creation and power operations. ```go // Create VM asynchronously op, err := client.VMs.CreateAsync(ctx, &vmmModels.Vm{ Spec: &vmmModels.VmSpec{ Name: "web-app-1", // ... more fields }, }) if err != nil { log.Fatal(err) } // Power operations powerOp, _ := client.VMs.PowerOnVM(vmUUID) results, _ := powerOp.Wait(ctx) ``` -------------------------------- ### Proxy Configuration Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Shows how to configure credentials to use a proxy server, emphasizing trusted corporate proxies. ```go // Only use for corporate proxies creds := prismgoclient.Credentials{ ProxyURL: os.Getenv("CORPORATE_PROXY"), } ``` -------------------------------- ### GetClusterStatus Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/konnector-api.md Example usage of the GetClusterStatus function. ```go status, err := client.ClusterRegistrationOperations.GetClusterStatus(ctx, clusterID) if err != nil { log.Fatal(err) } log.Printf("Status: %s, Heartbeat: %v", status.Status, status.LastHeartbeat) ``` -------------------------------- ### Lister Examples Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Examples of listing VMs, with and without filters, and using an iterator. ```go // List all VMs vms, err := client.VMs.List(ctx) // List with filtering vms, err := client.VMs.List(ctx, WithFilter("name eq 'web-vm'"), WithLimit(10), ) // Use iterator for large result sets iter := client.VMs.NewIterator(ctx, WithFilter("state eq 'running'")) for vm, err := range iter { if err != nil { log.Fatal(err) } log.Println(vm) } ``` -------------------------------- ### Certificate Verification Example (Development) Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example showing how to disable SSL certificate verification for development or testing environments. ```go credentials.Insecure = true // Development only ``` -------------------------------- ### Topology Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/types.md An example of creating a Topology map to specify a region and zone. ```go topology := converged.Topology{ "region": "us-east-1", "zone": "zone-a", } ``` -------------------------------- ### RegisterCluster Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/konnector-api.md Example usage of the RegisterCluster function. ```go req := &konnector.ClusterRegistrationRequest{ ClusterName: "production-k8s", ClusterUUID: "uuid-12345", Endpoint: "https://k8s.example.com:6443", Kubeconfig: kubeConfigBytes, } resp, err := client.ClusterRegistrationOperations.RegisterCluster(ctx, req) if err != nil { log.Fatal(err) } log.Printf("Registered: %s", resp.Status) ``` -------------------------------- ### WithUserAgent Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/internal-client.md Example of using WithUserAgent to set a custom User-Agent string. ```go client, _ := internal.NewClient( internal.WithUserAgent("nutanix/v3"), ) ``` -------------------------------- ### WithAbsolutePath Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/internal-client.md Example of using WithAbsolutePath to set an API path prefix. ```go client, _ := internal.NewClient( internal.WithAbsolutePath("api/nutanix/v3"), ) // Paths will be under: https://prism.example.com/api/nutanix/v3/ ``` -------------------------------- ### API Key Security Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Demonstrates loading an API key from an environment variable for secure authentication. ```go // Load from environment apiKey := os.Getenv("NUTANIX_API_KEY") creds := prismgoclient.Credentials{ Endpoint: "prism.example.com", APIKey: apiKey, } ``` -------------------------------- ### WithLogger Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/types.md Example of a functional option to configure a logger for a client. ```Go func WithLogger(logger *logr.Logger) types.ClientOption[v3.Client] { return func(c *v3.Client) error { c.clientOpts = append(c.clientOpts, internal.WithLogger(logger)) return nil } } ``` -------------------------------- ### Complete Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/konnector-api.md A comprehensive example demonstrating client initialization, metadata retrieval, cluster registration, and status checking. ```go package main import ( "context" "log" "github.com/nutanix-cloud-native/prism-go-client" "github.com/nutanix-cloud-native/prism-go-client/konnector" ) func main() { ctx := context.Background() // Initialize Konnector client creds := prismgoclient.Credentials{ URL: "konnector.example.com", Username: "admin", Password: "password", } client, err := konnector.NewKonnectorAPIClient(creds) if err != nil { log.Fatalf("Failed to create client: %v", err) } // Get metadata meta, err := client.Meta.GetMeta(ctx) if err != nil { log.Fatalf("Failed to get metadata: %v", err) } log.Printf("Konnector Version: %s", meta.Version) // Register cluster regReq := &konnector.ClusterRegistrationRequest{ ClusterName: "prod-k8s", ClusterUUID: "uuid-12345", Endpoint: "https://k8s.prod.internal", Kubeconfig: loadKubeconfig(), } regResp, err := client.ClusterRegistrationOperations.RegisterCluster(ctx, regReq) if err != nil { log.Fatalf("Failed to register cluster: %v", err) } log.Printf("Cluster registered: %s", regResp.ClusterID) // Get cluster status status, err := client.ClusterRegistrationOperations.GetClusterStatus(ctx, regResp.ClusterID) if err != nil { log.Fatalf("Failed to get status: %v", err) } log.Printf("Cluster Status: %s, Last Heartbeat: %v", status.Status, status.LastHeartbeat) } func loadKubeconfig() []byte { // Load from file or environment return []byte{} } ``` -------------------------------- ### ClustersService Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example usage of the ClustersService to list clusters and virtual GPUs. ```go clusters, err := client.Clusters.List(ctx, WithLimit(20)) if err != nil { log.Fatal(err) } gpus, err := client.Clusters.ListClusterVirtualGPUs(ctx, clusterUUID) ``` -------------------------------- ### WithExpand Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example of expanding related entities in the response. ```go vms, err := client.VMs.List(ctx, WithExpand("host")) ``` -------------------------------- ### WithLimit Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example of setting the maximum number of results per page. ```go vms, err := client.VMs.List(ctx, WithLimit(50)) ``` -------------------------------- ### VMConsoleToken Usage Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/types.md Example of generating and using a VM console token. ```Go token, _ := client.VMs.GenerateConsoleToken(ctx, vmUUID) // Connect to: ws://prism-central:9440{token.WsUri} // Headers: Authorization: Bearer {token.Token} ``` -------------------------------- ### NewKonnectorAPIClient Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/konnector-api.md Example of initializing the Konnector API client with credentials. ```go creds := prismgoclient.Credentials{ URL: "konnector.example.com", Username: "admin", Password: "password123", } client, err := konnector.NewKonnectorAPIClient(creds) if err != nil { log.Fatal(err) } // Use client meta, err := client.Meta.GetMeta(ctx) ``` -------------------------------- ### Iterator Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/types.md An example of using the Iterator to fetch and process a stream of VMs. ```go iter := client.VMs.NewIterator(ctx, WithFilter("state eq 'running'")) for vm, err := range iter { if err != nil { log.Fatal(err) } process(vm) } ``` -------------------------------- ### Basic Authentication (Username/Password) Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example of creating a V4 client using basic authentication with username and password. ```go credentials := prismgoclient.Credentials{ Endpoint: "prism-central.example.com", Username: "admin", Password: "password123", } v4Client, err := v4.NewV4Client(credentials) ``` -------------------------------- ### WithCertificate Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/konnector-api.md Example of using WithCertificate to add a custom certificate. ```go cert, _ := parseCertificateFromPEM(certBytes) client, _ := konnector.NewKonnectorAPIClient(creds, konnector.WithCertificate(cert)) ``` -------------------------------- ### SubnetsService Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example usage of the SubnetsService for reserving IPs and listing reserved IPs. ```go // Reserve IPs on subnet spec := &subnetModels.IpReserveSpec{ // ... specification } taskRef, _ := client.Subnets.ReserveIpsBySubnetId(ctx, subnetUUID, spec) // List reserved IPs reserved, _ := client.Subnets.ListReservedIpsBySubnetId(ctx, subnetUUID) ``` -------------------------------- ### V4 Client with API Key Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example of configuring a V4 client using an API key. ```go credentials := prismgoclient.Credentials{ Endpoint: "prism.prod.example.com", APIKey: "your-api-key-here", } client, err := v4.NewV4Client(credentials) ``` -------------------------------- ### Operation Polling Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example demonstrating how to poll an operation for completion. ```go op, err := client.VMs.CreateAsync(ctx, vm) // Poll-based approach for { if op.IsDone() { if op.IsSuccess() { results, _ := op.Results() log.Printf("Success: %v", results) } else { errors := op.Errors() log.Printf("Failed: %v", errors) } break } time.Sleep(1 * time.Second) } ``` -------------------------------- ### GetMeta Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/konnector-api.md Example of retrieving metadata using the GetMeta function. ```go meta, err := client.Meta.GetMeta(ctx) if err != nil { log.Fatal(err) } log.Printf("Version: %s", meta.Version) ``` -------------------------------- ### Pagination Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md Demonstrates how to paginate results when listing VMs. ```go vms, err := client.VMs.List(ctx, converged.WithPage(0), converged.WithLimit(50), ) ``` -------------------------------- ### V3 Client Configuration Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example of configuring a V3 client with endpoint, username, and password. ```go credentials := prismgoclient.Credentials{ Endpoint: "prism-central.example.com", Username: "admin", Password: "password", } v3Client, err := v3.NewV3Client(credentials) if err != nil { log.Fatal(err) } vms, err := v3Client.V3.ListVM(context.Background(), nil) ``` -------------------------------- ### WithBaseURL Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/internal-client.md Example of using WithBaseURL to set the base URL, demonstrating automatic HTTPS scheme addition. ```go client, _ := internal.NewClient( internal.WithBaseURL("prism.example.com"), ) // Base URL: https://prism.example.com/ ``` -------------------------------- ### Basic V4 Client Configuration Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example of configuring a V4 client with endpoint, username, password, and an optional port. ```go credentials := prismgoclient.Credentials{ Endpoint: "10.0.0.1", Username: "admin", Password: "nutanix/4u", Port: "9440", // Optional, defaults to 9440 } client, err := v4.NewV4Client(credentials) if err != nil { log.Fatal(err) } clusters, err := client.Clusters.List(context.Background()) ``` -------------------------------- ### Handle Not Found Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example demonstrating how to handle 'Not Found' errors when fetching a cluster, with logic to create it if it doesn't exist. ```go cluster, err := client.Clusters.Get(ctx, uuid) if converged.IsNotFound(err) { log.Printf("Cluster %s not found, creating...", uuid) // Create new cluster } else if err != nil { log.Fatal(err) } ``` -------------------------------- ### Example Usage of AdditionalFilter Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Demonstrates how to use AdditionalFilter to filter subnets by state. ```go filters := []*prismgoclient.AdditionalFilter{ {Name: "state", Values: []string{"RUNNING"}}, } subnets, _ := v3Client.V3.ListAllSubnet(ctx, "", filters) ``` -------------------------------- ### Task Error Checking Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example demonstrating how to check for task-related errors. ```go op, err := client.VMs.CreateAsync(ctx, vm) if err != nil { log.Fatal(err) } // Non-blocking check results, err := op.Results() if err != nil { if err == converged.ErrTaskResultsNotReady { log.Println("Task still running") } else if err == converged.ErrTaskFailed { log.Println("Task failed:", op.Errors()) } } // Blocking wait results, err := op.Wait(ctx) if err != nil { log.Fatal(err) } ``` -------------------------------- ### API Key Authentication (V3/V4) Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example of creating a V4 client using API Key authentication. ```go credentials := prismgoclient.Credentials{ Endpoint: "prism-central.example.com", APIKey: "a1b2c3d4e5f6g7h8", } v4Client, err := v4.NewV4Client(credentials) ``` -------------------------------- ### Error Checking Functions Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example demonstrating the usage of error checking functions. ```go cluster, err := client.Clusters.Get(ctx, uuid) if converged.IsNotFound(err) { log.Println("Cluster not found") } else if converged.IsRateLimit(err) { // Implement backoff time.Sleep(time.Second) } else if err != nil { log.Fatal(err) } ``` -------------------------------- ### OptsToV4ODataParams Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example demonstrating the use of OptsToV4ODataParams with functional options like WithFilter and WithLimit. ```go params, err := OptsToV4ODataParams( WithFilter("name eq 'web'"), WithLimit(10), WithOrderBy("name asc"), ) ``` -------------------------------- ### WithCertificate Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/internal-client.md Example of using WithCertificate to add a custom certificate for TLS verification. ```go cert, _ := parseCertFromPEM(certBytes) client, _ := internal.NewClient( internal.WithCertificate(cert), ) ``` -------------------------------- ### WithCookies Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/internal-client.md Example of using WithCookies to set session cookies for requests. ```go cookies := []*http.Cookie{ {Name: "sessionid", Value: "abc123"}, } client, _ := internal.NewClient(internal.WithCookies(cookies)) ``` -------------------------------- ### V3 API Client Initialization and VM Listing Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md Example of initializing the V3 API client and listing VMs. ```go import "github.com/nutanix-cloud-native/prism-go-client/v3" client, _ := v3.NewV3Client(creds) vms, _ := client.V3.ListVM(ctx, nil) ``` -------------------------------- ### V3 Certificate Errors Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example demonstrating how to handle certificate errors when creating a V3 client. ```go client, err := v3.NewV3Client(creds, v3.WithPEMEncodedCertBundle(certBytes)) if err != nil { log.Println("Certificate error:", err) } ``` -------------------------------- ### APIError Usage Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/types.md Example demonstrating how to check for specific API errors. ```Go cluster, err := client.Clusters.Get(ctx, uuid) if err != nil { apiErr := err.(*APIError) if errors.Is(apiErr, ErrNotFound) { log.Println("Not found") } } ``` -------------------------------- ### WithPEMEncodedCertBundle Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/konnector-api.md Example of using WithPEMEncodedCertBundle to add a bundle of PEM-encoded certificates. ```go certBundle := []byte(`-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----`) client, _ := konnector.NewKonnectorAPIClient(creds, konnector.WithPEMEncodedCertBundle(certBundle)) ``` -------------------------------- ### Developer Configuration File Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/DEVELOPMENT.md Example YAML structure for the .prism-dev.yaml file to override default configuration values for local development and unit testing. ```yaml prismCentral: endpoint: port: username: password: insecure: ``` -------------------------------- ### Operation Blocking Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example demonstrating the blocking Wait method for an operation. ```go results, err := op.Wait(ctx) ``` -------------------------------- ### VolumeGroupsService Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example usage of the VolumeGroupsService for attaching and detaching volume groups to/from VMs. ```go // Attach volume group to VM op, err := client.VolumeGroups.AttachToVMAsync(ctx, volumeUUID, attachment) results, _ := op.Wait(ctx) // Detach detachOp, _ := client.VolumeGroups.DetachFromVMAsync(ctx, volumeUUID, attachment) ``` -------------------------------- ### CopyEtag Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example demonstrating how to copy an ETag from an original VM object to an updated object before performing an update operation. ```go original, _ := client.VMs.Get(ctx, uuid) updated := copyVM(original) updated = CopyEtag(original, updated) result, _ := client.VMs.Update(ctx, uuid, updated) ``` -------------------------------- ### Error Handling - Example Usage Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example of how to check for specific errors using helper functions. ```go _ := client.VMs.Get(ctx, invalidUUID) if converged.IsNotFound(err) { log.Println("VM not found") } else if err != nil { log.Fatal(err) } ``` -------------------------------- ### GetEtag Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example showing how to retrieve an ETag from a VM object and its potential use in an If-Match header for updates. ```go vm, _ := client.VMs.Get(ctx, uuid) etag := GetEtag(vm) // Use etag in If-Match header for updates ``` -------------------------------- ### WithRoundTripper Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/konnector-api.md Example of using WithRoundTripper to provide a custom HTTP transport. ```go mockTransport := &mockHTTPTransport{...} client, _ := konnector.NewKonnectorAPIClient(creds, konnector.WithRoundTripper(mockTransport)) ``` -------------------------------- ### AdditionalFilter Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/types.md An example demonstrating the creation of an AdditionalFilter slice for filtering resources by state. ```go filters := []*prismgoclient.AdditionalFilter{ {Name: "state", Values: []string{"RUNNING", "PAUSED"}}, } ``` -------------------------------- ### V4 Client with Proxy Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example of configuring a V4 client to use an HTTP proxy. ```go credentials := prismgoclient.Credentials{ Endpoint: "prism.example.com", Username: "admin", Password: "password", ProxyURL: "http://proxy.internal.example.com:8080", } client, err := v4.NewV4Client(credentials) ``` -------------------------------- ### Konnector API Initialization Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example of initializing a Konnector API client with credentials and handling potential initialization errors. ```go client, err := konnector.NewKonnectorAPIClient(creds) if err != nil { // Error: "konnector Client is missing: Please provide required details - url, username in provider configuration" log.Fatal(err) } ``` -------------------------------- ### Filtering Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md Shows how to filter VM results based on specific criteria. ```go vms, err := client.VMs.List(ctx, converged.WithFilter("name eq 'web-1' and state eq 'running'"), ) ``` -------------------------------- ### V4 Client with Custom Certificate Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example of configuring a V4 client to use a custom certificate bundle and verify SSL. ```go certBundle := loadCertificateBundle() credentials := prismgoclient.Credentials{ Endpoint: "prism.internal.example.com", Username: "admin", Password: "password", Insecure: false, // Verify SSL } client, err := v4.NewV4Client(credentials, v4.WithPEMEncodedCertBundle(certBundle)) ``` -------------------------------- ### WithPEMEncodedCertBundle Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/v3-api.md Example of using the WithPEMEncodedCertBundle option to add multiple PEM-encoded certificates. ```go certBundle := []byte(`-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----`) client, _ := v3.NewV3Client(creds, v3.WithPEMEncodedCertBundle(certBundle)) ``` -------------------------------- ### WithLogger Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/v3-api.md Example of using the WithLogger option to set a structured logger for the client. ```go zapLogger, _ := zap.NewProduction() wrappedLogger := zapr.NewLogger(zapLogger) client, _ := v3.NewV3Client(creds, v3.WithLogger(&wrappedLogger)) ``` -------------------------------- ### V3 API Errors Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example demonstrating how to handle API errors returned from V3 operations. ```go vms, err := v3Client.V3.ListVM(ctx, nil) if err != nil { log.Println("API Error:", err) // Check error string for specific conditions if strings.Contains(err.Error(), "401") { log.Println("Authentication failed") } } ``` -------------------------------- ### Category Operations Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/v3-api.md Example demonstrating how to create a category key and a category value using the Prism Go Client. ```go // Create category key key := &v3.CategoryKey{ Description: "Environment", Name: "Environment", } status, _ := v3Client.V3.CreateOrUpdateCategoryKey(ctx, key) // Create category value val := &v3.CategoryValue{Name: "production"} valStatus, _ := v3Client.V3.CreateOrUpdateCategoryValue(ctx, "Environment", val) ``` -------------------------------- ### WithFilter Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-api.md Example of setting an OData filter expression to filter by name and state. ```go // Filter by name and state vms, err := client.VMs.List(ctx, WithFilter("name eq 'web-1' and state eq 'running'")) ``` -------------------------------- ### WithUserAgent Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/v3-api.md Example of using the WithUserAgent option to set a custom user agent string. ```go client, _ := v3.NewV3Client(creds, v3.WithUserAgent("my-app/1.0.0")) ``` -------------------------------- ### APIError Checking Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example demonstrating how to check for specific API errors using the APIError type. ```go vm, err := client.VMs.Get(ctx, uuid) if err != nil { apiErr, ok := err.(*converged.APIError) if ok { if apiErr.Is(converged.ErrNotFound) { log.Println("VM not found") } else if apiErr.Is(converged.ErrRateLimit) { log.Println("Rate limited, retry later") } } log.Fatal(err) } ``` -------------------------------- ### WithCertificate Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/v3-api.md Example of using the WithCertificate option to add a certificate to the client's pool. ```go cert, _ := parseCertificateFromPEM(certBytes) client, _ := v3.NewV3Client(creds, v3.WithCertificate(cert)) ``` -------------------------------- ### UnregisterCluster Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/konnector-api.md Example usage of the UnregisterCluster function. ```go err := client.ClusterRegistrationOperations.UnregisterCluster(ctx, clusterID) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Konnector Client Configuration Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example of configuring a Konnector client with URL, username, and password. ```go credentials := prismgoclient.Credentials{ URL: "konnector.internal.example.com", Username: "admin", Password: "password", } kcClient, err := konnector.NewKonnectorAPIClient(credentials) if err != nil { log.Fatal(err) } meta, err := kcClient.Meta.GetMeta(context.Background()) ``` -------------------------------- ### Converged V4 API Client Initialization and VM Listing Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md Example of initializing the Converged V4 API client and listing VMs. ```go import "github.com/nutanix-cloud-native/prism-go-client/converged/v4" creds := prismgoclient.Credentials{ Endpoint: "prism.example.com", Username: "admin", Password: "password", } client, _ := v4.NewClient(creds) vms, _ := client.VMs.List(ctx) ``` -------------------------------- ### Service Error Example: List Cluster Virtual GPUs Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example demonstrating error handling for listing cluster virtual GPUs, specifically checking for unsupported OData options. ```go gpus, err := client.Clusters.ListClusterVirtualGPUs(ctx, "", WithApply("groupby((model))")) if err != nil { // Error: "apply, expand and select are not supported" } ``` -------------------------------- ### NewHTTPClient Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/nusights-api.md Creates a new NuSights HTTP client with default configuration. ```Go import "github.com/go-openapi/strfmt" formats := strfmt.Default client := nusights.NewHTTPClient(formats) ``` -------------------------------- ### WithRoundTripper Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/v3-api.md Example of using the WithRoundTripper option to override the HTTP transport, useful for testing. ```go mockTransport := &mockHTTPTransport{...} client, _ := v3.NewV3Client(creds, v3.WithRoundTripper(mockTransport)) ``` -------------------------------- ### ConvertTaskStatus Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Example showing how a task status obtained from an asynchronous VM creation operation is already converted to the converged.TaskStatus type. ```go operation, _ := client.VMs.CreateAsync(ctx, vm) status := operation.Status() // status is already converted to converged.TaskStatus ``` -------------------------------- ### Password Management: Good Practice Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Illustrates the recommended practice of loading passwords from environment variables instead of hardcoding them. ```go // BAD creds := prismgoclient.Credentials{ Password: "hardcoded123", } // GOOD creds := prismgoclient.Credentials{ Password: os.Getenv("NUTANIX_PASSWORD"), } ``` -------------------------------- ### NuSights API Client Initialization and Configuration Retrieval Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md Example of initializing the NuSights API client and retrieving configuration data. ```go import "github.com/nutanix-cloud-native/prism-go-client/nusights/client" client := nusights.NewHTTPClient(strfmt.Default) config, _ := client.Config.GetConfigData(ctx) ``` -------------------------------- ### WithSchemes Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/nusights-api.md Sets supported HTTP schemes. Chainable method. ```Go cfg := nusights.DefaultTransportConfig(). WithSchemes([]string{"https"}) ``` -------------------------------- ### Konnector Authentication Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example of creating a Konnector API client using URL, username, and password. ```go credentials := prismgoclient.Credentials{ URL: "konnector.example.com", Username: "admin", Password: "password123", } kcClient, err := konnector.NewKonnectorAPIClient(credentials) ``` -------------------------------- ### WithHost Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/nusights-api.md Sets a custom host for the API endpoint. Chainable method. ```Go cfg := nusights.DefaultTransportConfig(). WithHost("insights.internal.example.com") client := nusights.NewHTTPClientWithConfig(strfmt.Default, cfg) ``` -------------------------------- ### Get HTTP Method Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/internal-client.md Performs HTTP GET request. Returns: Error if request fails or response is invalid. ```go func (c *Client) Get(ctx.Context, urlPath string, headers map[string]string, resource interface{}) error ``` ```go var vm interface{} err := client.Get(ctx, "/vms/uuid-123", nil, &vm) ``` -------------------------------- ### Streaming Results Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md Shows how to use an iterator to stream results, which is useful for large datasets. ```go iter := client.VMs.NewIterator(ctx, converged.WithFilter("state eq 'running'")) for vm, err := range iter { if err != nil { log.Fatal(err) } process(vm) } ``` -------------------------------- ### NewHTTPClientWithConfig Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/nusights-api.md Creates a new NuSights client with custom transport configuration. ```Go cfg := &nusights.TransportConfig{ Host: "custom-insights.internal", BasePath: "/api/nutanix/insights/v1", Schemes: []string{"https"}, } client := nusights.NewHTTPClientWithConfig(strfmt.Default, cfg) ``` -------------------------------- ### Async Operations Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md Illustrates how to perform asynchronous operations and wait for completion or poll for status. ```go op, err := client.VMs.CreateAsync(ctx, vmSpec) results, err := op.Wait(ctx) // Blocking // OR for !op.IsDone() { time.Sleep(1 * time.Second) // Polling } results, _ := op.Results() ``` -------------------------------- ### V4 Client with Insecure Mode (Self-Signed Certificates) Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Example of configuring a V4 client to skip SSL verification for self-signed certificates. ```go credentials := prismgoclient.Credentials{ Endpoint: "prism.local", Username: "admin", Password: "password", Insecure: true, // Skip SSL verification } client, err := v4.NewV4Client(credentials) ``` -------------------------------- ### Async Operation Error Handling Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example of handling errors for asynchronous operations, including waiting for completion and checking for specific operation failures. ```go op, err := client.VMs.CreateAsync(ctx, vm) if err != nil { log.Fatal(err) } results, err := op.Wait(context.WithTimeout(ctx, 5*time.Minute)) if err != nil { if op.IsFailed() { errors := op.Errors() log.Printf("Creation failed with %d errors:", len(errors)) for _, e := range errors { log.Printf(" - %v", e) } } log.Fatal(err) } ``` -------------------------------- ### Error Handling Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/konnector-api.md Demonstrates how to handle common errors when unregistering a cluster. ```go err := client.ClusterRegistrationOperations.UnregisterCluster(ctx, invalidID) if err != nil { if strings.Contains(err.Error(), "cluster not found") { log.Println("Cluster not registered") } else { log.Fatal(err) } } ``` -------------------------------- ### Konnector API Client Initialization and Metadata Retrieval Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md Example of initializing the Konnector API client and retrieving metadata. ```go import "github.com/nutanix-cloud-native/prism-go-client/konnector" client, _ := konnector.NewKonnectorAPIClient(creds) meta, _ := client.Meta.GetMeta(ctx) ``` -------------------------------- ### Error Handling Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md Demonstrates common error handling patterns for API calls, including checking for specific error types like NotFound and RateLimit. ```go vm, err := client.VMs.Get(ctx, uuid) if converged.IsNotFound(err) { // Handle not found } else if converged.IsRateLimit(err) { // Handle rate limit with backoff } else if err != nil { // Handle other errors } ``` -------------------------------- ### GetConfigData Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/nusights-api.md Retrieves current insights configuration data. ```Go cfg, err := client.Config.GetConfigData(ctx) if err != nil { log.Fatal(err) } log.Printf("Config: %+v", cfg.Data) ``` -------------------------------- ### WithBasePath Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/nusights-api.md Sets a custom base path for API requests. Chainable method. ```Go cfg := nusights.DefaultTransportConfig(). WithBasePath("/api/nutanix/insights/v2") ``` -------------------------------- ### Retry Logic for Rate Limiting Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example implementation of retry logic for handling rate limiting errors when fetching VM data. ```go import "time" func getWithRetry(uuid string, maxRetries int) (*converged.VM, error) { for attempt := 0; attempt < maxRetries; attempt++ { vm, err := client.VMs.Get(ctx, uuid) if converged.IsRateLimit(err) { backoff := time.Duration(1 << uint(attempt)) * time.Second log.Printf("Rate limited, retrying in %v", backoff) time.Sleep(backoff) continue } return vm, err } return nil, converged.ErrRateLimit } ``` -------------------------------- ### Loading Credentials from Environment Variables Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Demonstrates how to initialize Prism Go Client credentials by reading values from environment variables. ```go credentials := prismgoclient.Credentials{ Endpoint: os.Getenv("PRISM_ENDPOINT"), Username: os.Getenv("PRISM_USERNAME"), Password: os.Getenv("PRISM_PASSWORD"), Insecure: os.Getenv("PRISM_INSECURE") == "true", ProxyURL: os.Getenv("HTTP_PROXY"), } client, err := v4.NewV4Client(credentials) ``` -------------------------------- ### V3 Client Options Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Provides various options for configuring the V3 client. ```go func WithCertificate(certificate *x509.Certificate) types.ClientOption[Client] func WithPEMEncodedCertBundle(certBundle []byte) types.ClientOption[Client] func WithRoundTripper(transport http.RoundTripper) types.ClientOption[Client] func WithLogger(logger *logr.Logger) types.ClientOption[Client] func WithUserAgent(userAgent string) types.ClientOption[Client] ``` -------------------------------- ### PutConfigData Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/nusights-api.md Example of updating insights configuration data using the PutConfigData method. ```go req := &nusights.ConfigDataRequest{ Data: insightsConfig, Merge: true, } resp, err := client.Config.PutConfigData(ctx, req) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Loading Credentials from Configuration File Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Shows how to load Prism Go Client credentials from a YAML configuration file. ```go import "gopkg.in/yaml.v3" type Config struct { Credentials struct { Endpoint string `yaml:"endpoint"` Username string `yaml:"username"` Password string `yaml:"password"` APIKey string `yaml:"api_key,omitempty"` Insecure bool `yaml:"insecure"` } `yaml:"credentials"` } func loadConfig(path string) (*Config, error) { data, _ := os.ReadFile(path) cfg := &Config{} err := yaml.Unmarshal(data, cfg) return cfg, err } // config.yaml // credentials: // endpoint: prism-central.example.com // username: admin // password: password // insecure: false ``` -------------------------------- ### Replaying API Calls with Keploy Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/DEVELOPMENT.md Go code snippet demonstrating how to use Keploy to replay previously recorded API calls for unit tests. It shows setting the Keploy context mode to TEST. ```go func TestMetaOperations_GetVersion(t *testing.T) { creds := testhelpers.CredentialsFromEnvironment(t) interceptor := khttpclient.NewInterceptor(http.DefaultTransport) kc, err := NewKonnectorAPIClient(creds, WithRoundTripper(interceptor)) require.NoError(t, err) kctx := mock.NewContext(mock.Config{ Mode: keploy.MODE_TEST, Name: t.Name(), }) v, err := kc.Meta.GetVersion(kctx) // Make the call to the API ... } ``` -------------------------------- ### Konnector Operation Error Checking Example Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/errors.md Example of checking for specific errors during Konnector API operations like UnregisterCluster, including handling 'not found' and 'connection' errors. ```go err := client.ClusterRegistrationOperations.UnregisterCluster(ctx, clusterID) if err != nil { if strings.Contains(err.Error(), "not found") { log.Println("Cluster doesn't exist") } else if strings.Contains(err.Error(), "connection") { log.Println("Connection error, will retry") } else { log.Fatal(err) } } ``` -------------------------------- ### V4 Client Validation Logic Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Illustrates the credential validation logic for the V4 client, checking for API key or basic auth requirements. ```go if credentials.APIKey != "" { // API key mode if credentials.Endpoint == "" { return nil, fmt.Errorf("endpoint is required for api key auth") } } else { // Basic auth mode if credentials.Username == "" || credentials.Password == "" || credentials.Endpoint == "" { return nil, fmt.Errorf("username, password and endpoint are required for basic auth") } } ``` -------------------------------- ### V3 Client Validation Logic Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/configuration.md Shows the credential validation logic for the V3 client, similar to V4. ```go if credentials.APIKey != "" { if credentials.Endpoint == "" { return nil, fmt.Errorf("endpoint is required for api key auth") } } else { if credentials.Username == "" || credentials.Password == "" || credentials.Endpoint == "" { return nil, fmt.Errorf("username, password and endpoint are required for basic auth") } } ``` -------------------------------- ### Client Initialization and Constants Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/v3-api.md Provides constants and source file information related to the v3 client initialization. ```go const ( libraryVersion = "v3" absolutePath = "api/nutanix/v3" userAgent = "nutanix/v3" ) ``` -------------------------------- ### GenericGetEntity Function Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/converged-v4-implementation.md Generic wrapper for synchronous GET operations. ```go func GenericGetEntity[R APIResponse, T any]( apiCall func() (R, error), entityName string) (*T, error) ``` -------------------------------- ### Recording API Calls with Keploy Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/DEVELOPMENT.md Go code snippet demonstrating how to use Keploy to intercept and record API calls to Prism Central for use as unit test mocks. It shows setting the Keploy context mode to RECORD. ```go func TestMetaOperations_GetVersion(t *testing.T) { // Get the credentials form the environment (or use the default ones) // This is useful for running the unit tests against a custom prism deployment // This will get the credentials from the .prism-dev.yaml file in your home directory // or from the file pointed to by the PRISM_DEV_CONFIG environment variable. // In the CI, we use the dummy credentials as it is always a replayed response. creds := testhelpers.CredentialsFromEnvironment(t) // create a keploy interceptor by wrapping a http RoundTripper interceptor := khttpclient.NewInterceptor(http.DefaultTransport) // Initialize the http client with the keploy interceptor as the round tripper kc, err := NewKonnectorAPIClient(creds, WithRoundTripper(interceptor)) require.NoError(t, err) // create a new keploy mock context with keploy mock config name set to the name of the unit test e.g. `t.Name()` // The default Mode is keploy.MODE_OFF, which means that keploy will not intercept any API calls. // The Mode can be set to keploy.MODE_RECORD to record API calls. // The Mode can be set to keploy.MODE_TEST to replay a previously recorded API call. // Here, we set the Mode to keploy.MODE_RECORD to record a new API call. kctx := mock.NewContext(mock.Config{ Mode: keploy.MODE_RECORD, Name: t.Name(), }) v, err := kc.Meta.GetVersion(kctx) // Make the call to the API ... } ``` -------------------------------- ### WithCredentials Function Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/api-reference/internal-client.md Function signature for setting authentication credentials. ```go func WithCredentials(credentials *prismgoclient.Credentials) ClientOption ``` -------------------------------- ### Managing Cluster Categories Source: https://github.com/nutanix-cloud-native/prism-go-client/blob/main/_autodocs/README.md Manages cluster categories, including getting and updating them. ```go // See: converged-api.md → Categories[Category] category, _ := client.Categories.Get(ctx, uuid) category.Value = "production" updated, _ := client.Categories.Update(ctx, uuid, category) ```