### Basic Credential Setup Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Shows how to set up basic credentials for authenticating with Huawei Cloud services. This often involves using environment variables for access key and secret access key. ```go os.Setenv("HUAWEICLOUD_SDK_AK", "YOUR_ACCESS_KEY") os.Setenv("HUAWEICLOUD_SDK_SK", "YOUR_SECRET_ACCESS_KEY") ``` -------------------------------- ### Complete Minimal Example - Go VPC Client Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/quick-start.md This example demonstrates how to initialize the Go SDK client for the VPC service, configure authentication, and make a call to list VPCs. Ensure environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK are set. ```go package main import ( "fmt" "log" "os" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic" vpc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/model" vpcRegion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/region" ) func main() { // Configure authentication auth, err := basic.NewCredentialsBuilder(). WithAk(os.Getenv("HUAWEICLOUD_SDK_AK")), WithSk(os.Getenv("HUAWEICLOUD_SDK_SK")), SafeBuild() if err != nil { log.Fatal(err) } // Get region region, err := vpcRegion.SafeValueOf("cn-north-4") if err != nil { log.Fatal(err) } // Create HTTP client hcClient, err := core.NewHcHttpClientBuilder(). WithRegion(region). WithCredential(auth). SafeBuild() if err != nil { log.Fatal(err) } // Create service client client := vpc.NewVpcClient(hcClient) // Call API response, err := client.ListVpcs(&model.ListVpcsRequest{}) if err != nil { log.Fatal(err) } if response.Vpcs != nil { fmt.Printf("Found %d VPCs\n", len(*response.Vpcs)) } } ``` -------------------------------- ### Install Huawei Cloud Go SDK Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README.md Run this command to install the Huawei Cloud Go SDK library. Ensure you have Go 1.14 or later installed. ```bash go get github.com/huaweicloud/huaweicloud-sdk-go-v3 ``` -------------------------------- ### Header Parameters Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/api-endpoints-reference.md Examples of common request headers, including the request ID and authentication token. ```go X-Request-Id: abc-123 X-Auth-Token: (added by credential) ``` -------------------------------- ### Example: Path Parameter Configuration Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Configures a FieldDef for a URL path parameter. ```go // Path parameter def.NewFieldDef(). WithName("VpcId"). WithJsonTag("vpc_id"). WithLocationType(def.Path) ``` -------------------------------- ### Proxy Configuration Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Illustrates how to configure proxy settings for the HTTP client. This is useful when the SDK needs to connect through a proxy server. ```go proxy := NewProxy("http", "your.proxy.host", 8080, "user", "password") config := DefaultHttpConfig() config.Proxy = proxy ``` -------------------------------- ### Example Usage of GetProxyUrl Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/configuration.md Demonstrates how to configure proxy settings and generate the proxy URL using chained method calls. ```go proxy := config.NewProxy(). WithSchema("http"). WithHost("proxy.corp.com"). WithPort(8080). WithUsername("alice"). WithPassword("secret") url := proxy.GetProxyUrl() // Output: http://alice:secret@proxy.corp.com:8080 ``` -------------------------------- ### Example: Header Parameter Configuration Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Configures a FieldDef for an HTTP header parameter. ```go // Header parameter def.NewFieldDef(). WithName("XRequestId"). WithJsonTag("x-request-id"). WithLocationType(def.Header) ``` -------------------------------- ### Example: Query Parameter Configuration Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Configures a FieldDef for a URL query string parameter. ```go // Query parameter def.NewFieldDef(). WithName("Limit"). WithJsonTag("limit"). WithLocationType(def.Query) ``` -------------------------------- ### HTTP Client Configuration Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Demonstrates how to configure the HTTP client used by the SDK. This can include setting timeouts, retry logic, and other transport-related options. ```go hcClient := NewHcHttpClientBuilder().WithTimeout(10*time.Second).Build() ``` -------------------------------- ### Example: Request Body Configuration Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Configures a FieldDef for the request body. ```go // Request body def.NewFieldDef(). WithName("Body"). WithLocationType(def.Body) ``` -------------------------------- ### Example Error: Failed to Get Project ID Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/authentication.md Illustrates the error message when the project ID cannot be automatically discovered for a region. It suggests setting the project ID manually. ```go failed to get project id of region 'cn-north-4' automatically: X-IAM-Trace-Id=abc-123, confirm that the project exists in your account, or set project id manually: basic.NewCredentialsBuilder().WithAk(ak).WithSk(sk).WithProjectId(projectId).SafeBuild() ``` -------------------------------- ### Build and Use Core HTTP Client Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/core-http-client.md Example demonstrating how to create credentials, select a region, build an HTTP client, and use it to instantiate a service client (VPC in this case) to execute a request. ```go package main import ( "fmt" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/model" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/region" ) func main() { // Create credentials credentials, _ := basic.NewCredentialsBuilder(). WithAk("your-ak"). WithSk("your-sk"). SafeBuild() // Get region r, _ := region.SafeValueOf("cn-north-4") // Build HTTP client httpClient, _ := core.NewHcHttpClientBuilder(). WithRegion(r). WithCredential(credentials). SafeBuild() // Create service client vpcClient := v2.NewVpcClient(httpClient) // Execute request response, err := vpcClient.ListVpcs(&model.ListVpcsRequest{}) if err != nil { fmt.Println("Error:", err) } else { fmt.Printf("Response: %+v\n", response) } } ``` -------------------------------- ### Request Body Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/api-endpoints-reference.md An example of a JSON request body for creating a VPC. ```json POST /v2.0/vpcs { "vpc": { "name": "...", "cidr": "..." } } ``` -------------------------------- ### Multi-Service Region Setup (Go) Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/region-management.md Demonstrates configuring clients for different services that might operate in different regions. It's important to fetch the correct region for each service. ```go // Regions may differ per service vpcRegion, _ := vpc_region.SafeValueOf("cn-north-4") ecsRegion, _ := ecs_region.SafeValueOf("cn-north-4") hcClient, _ := vpc.VpcClientBuilder(). WithRegion(vpcRegion). WithCredential(creds). SafeBuild() vpcClient := vpc.NewVpcClient(hcClient) ecsClient := ecs.NewEcsClient(hcClient) ``` -------------------------------- ### WithJsonTag Usage Examples Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Illustrates how to use WithJsonTag for different HTTP parameter types. ```go WithJsonTag("vpc_id") // For path/query parameters WithJsonTag("x-request-id") // For headers (lowercase) ``` -------------------------------- ### Region Management Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Shows how to configure the region for service endpoints. This allows the SDK to connect to the correct regional endpoint for a given service. ```go region := NewRegion("cn-north-1", "https://vpc.cn-north-1.myhuaweicloud.com") ``` -------------------------------- ### Service Client Creation Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Demonstrates how to create a new client for a specific Huawei Cloud service. This typically involves using a service constructor function, such as `NewVpcClient`, which may require configuration options. ```go client := NewVpcClient(opts...) ``` -------------------------------- ### Go SDK Workflow Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/OVERVIEW.md Demonstrates the typical workflow for using the Huawei Cloud Go SDK, including creating credentials, configuring the HTTP client, initializing a service client, and executing an API call. ```go // 1. Create credentials creds, _ := basic.NewCredentialsBuilder(). WithAk(ak). WithSk(sk). SafeBuild() // 2. Configure HTTP client hcClient, _ := vpc.VpcClientBuilder(). WithRegion(region). WithCredential(creds). SafeBuild() // 3. Create service client client := vpc.NewVpcClient(hcClient) // 4. Execute API call response, _ := client.ListVpcs(&model.ListVpcsRequest{}) ``` -------------------------------- ### Go SDK Quick Start: List VPCs Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/README.md This Go program demonstrates how to initialize the SDK, authenticate using environment variables, and list Virtual Private Clouds (VPCs) in a specified region. Ensure HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK environment variables are set. ```go package main import ( "fmt" "log" "os" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic" vpc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/model" vpcRegion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/region" ) func main() { // 1. Create credentials from environment auth, _ := basic.NewCredentialsBuilder(). WithAk(os.Getenv("HUAWEICLOUD_SDK_AK")), WithSk(os.Getenv("HUAWEICLOUD_SDK_SK")), SafeBuild() // 2. Get region region, _ := vpcRegion.SafeValueOf("cn-north-4") // 3. Build HTTP client hcClient, _ := core.NewHcHttpClientBuilder(). WithRegion(region). WithCredential(auth). SafeBuild() // 4. Create service client client := vpc.NewVpcClient(hcClient) // 5. Call API response, err := client.ListVpcs(&model.ListVpcsRequest{}) if err != nil { log.Fatal(err) } if response.Vpcs != nil { for _, vpc := range *response.Vpcs { fmt.Printf("VPC: %s (%s)\n", vpc.Name, vpc.Id) } } } ``` -------------------------------- ### Example: Form Data Configuration Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Configures a FieldDef for form data, typically used for file uploads. ```go // Form data def.NewFieldDef(). WithName("FileData"). WithJsonTag("file"). WithLocationType(def.Form) ``` -------------------------------- ### Build HTTP Client Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/service-clients.md Construct an HTTP client for the service, configuring it with the selected region and credentials. The VpcClientBuilder is used as an example. ```go hcClient, _ := vpc_v2.VpcClientBuilder(). WithRegion(region). WithCredential(creds). SafeBuild() ``` -------------------------------- ### Synchronous API Call Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/service-clients.md Demonstrates how to execute a synchronous API call to list VPCs and process the response. Ensure proper error handling. ```go response, err := vpcClient.ListVpcs(&model.ListVpcsRequest{}) if err != nil { log.Fatal(err) } for _, vpc := range response.Vpcs { fmt.Printf("VPC: %s (%s)\n", vpc.Name, vpc.Id) } ``` -------------------------------- ### Basic Region Configuration (Go) Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/region-management.md Demonstrates how to get a region object by its ID and use it to build a client. Ensure the region ID is valid and supported. ```go import ( vpc_region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/region" ) func main() { // Get region by ID region, err := vpc_region.SafeValueOf("cn-north-4") if err != nil { log.Fatalf("Region not found: %v", err) } hcClient, _ := VpcClientBuilder(). WithRegion(region). WithCredential(creds). SafeBuild() } ``` -------------------------------- ### NewBasicCredentialsBuilder Constructor Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/authentication.md Initializes a new instance of the BasicCredentialsBuilder. Use this to start building your credentials. ```go func NewBasicCredentialsBuilder() *BasicCredentialsBuilder ``` -------------------------------- ### Service Request and Response Models Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/types.md Illustrates the structure of typical request and response objects for services, such as listing VPCs. Includes example resource structure. ```go // Request type ListVpcsRequest struct { Limit *int32 `json:"limit,omitempty"` Marker *string `json:"marker,omitempty"` } // Response type ListVpcsResponse struct { Vpcs *[]Vpc `json:"vpcs,omitempty"` HttpStatusCode int `json:"-"` } // Resource type Vpc struct { Id *string `json:"id,omitempty"` Name *string `json:"name,omitempty"` Cidr *string `json:"cidr,omitempty"` Status *string `json:"status,omitempty"` CreatedAt *string `json:"created_at,omitempty"` } ``` -------------------------------- ### Pagination Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Illustrates how to handle paginated results from API calls. This typically involves iterating through pages of results until all items are retrieved. ```go for resp.PageInfo.NextMarker != "" { request.Marker = resp.PageInfo.NextMarker resp, err = client.ListVpcs(ctx, &request, &response) // Process results } ``` -------------------------------- ### Configure Multi-Region Client in Go SDK Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/INDEX.md Dynamically build service clients for different regions. This example iterates through a list of region IDs, safely retrieves region configurations, and builds a client for each. ```go for _, regionId := range []string{"cn-north-4", "cn-east-2"} { region, _ := svc_region.SafeValueOf(regionId) client, _ := svc.SvcClientBuilder(). WithRegion(region). WithCredential(creds). SafeBuild() // Use client... } ``` -------------------------------- ### Send Request and Handle Response Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README.md Example of sending a request to list VPCs and handling the response. It demonstrates how to create a request object, send it using the client, and process the results or errors. ```go // send a request and print response, take interface of ListVpcs for example limit := int32(1) request := &model.ListVpcsRequest{ Limit: &limit, } response, err := client.ListVpcs(request) if err == nil { fmt.Printf("%+v\n\n", response.Vpcs) } else { fmt.Println(err) } ``` -------------------------------- ### Full Usage Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Demonstrates how to use the HttpRequestDefBuilder to define a complex request, including method, path, response type, and multiple request fields with specific locations. ```go // Define request for batch operation reqDef := def.NewHttpRequestDefBuilder(). WithMethod(http.MethodPost). WithPath("/v2.0/{project_id}/security-groups/{sg_id}/tags/action"). WithResponse(new(model.BatchCreateSecurityGroupTagsResponse)). WithContentType("application/json;charset=UTF-8"). WithRequestField(def.NewFieldDef(). WithName("ProjectId"). WithJsonTag("project_id"). WithLocationType(def.Path)). WithRequestField(def.NewFieldDef(). WithName("SecurityGroupId"). WithJsonTag("sg_id"). WithLocationType(def.Path)). WithRequestField(def.NewFieldDef(). WithName("Body"). WithLocationType(def.Body)). Build() ``` -------------------------------- ### Retry Logic Configuration Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Demonstrates how to configure retry logic for API calls. This allows the SDK to automatically retry failed requests under certain conditions, improving resilience. ```go config := DefaultHttpConfig() config.RetryCount = 3 ``` -------------------------------- ### Example Error: Multiple Project IDs Found Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/authentication.md Shows the error message when multiple project IDs are found for a region. It advises selecting one during credential initialization. ```go multiple project ids found: [project-1, project-2], X-IAM-Trace-Id=abc-123, please select one when initializing the credentials ``` -------------------------------- ### Import Service Packages Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/service-clients.md Import the specific service client packages for the services you intend to use. This example shows importing clients for VPC and ECS services. ```go import vpc_v2 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2" import ecs_v1 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v1" ``` -------------------------------- ### Set Huawei Cloud SDK Environment Variables Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/README.md Before running the Go SDK example, set your Huawei Cloud Access Key (AK) and Secret Key (SK) as environment variables. This is required for authentication. ```bash export HUAWEICLOUD_SDK_AK="your-access-key" export HUAWEICLOUD_SDK_SK="your-secret-key" ``` -------------------------------- ### Custom Endpoint Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Shows how to specify a custom endpoint for a service, overriding the default regional endpoint. This is useful for testing or connecting to private endpoints. ```go region := NewRegion("custom-region", "https://my.custom.endpoint.com") ``` -------------------------------- ### Get Credentials from Instance Metadata Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README.md Obtain temporary AK/SK and security token from instance metadata. Use BasicCredentialMetadataProvider for basic credentials and GlobalCredentialMetadataProvider for global credentials. ```go import "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/provider" // basic basicProvider := provider.BasicCredentialMetadataProvider() basicCred, err := basicProvider.GetCredentials() // global globalProvider := provider.GlobalCredentialMetadataProvider() globalCred, err := globalProvider.GetCredentials() ``` -------------------------------- ### API Call Pattern Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Illustrates the general pattern for making API calls to Huawei Cloud services using the SDK. This involves obtaining a service client and then invoking specific API methods on that client. ```go resp, err := client.ListVpcs(ctx, &request, &response) ``` -------------------------------- ### ListVpcs Operation Request Definition Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Example of generating an HttpRequestDef for the ListVpcs operation, which is a GET request to retrieve VPCs. ```APIDOC ## ListVpcs Operation ### Description Generates the HTTP request definition for listing VPCs. ### Method GET ### Endpoint /v2.0/vpcs ### Request Example ```go // Generated for VPC ListVpcs operation GenReqDefForListVpcs := def.NewHttpRequestDefBuilder(). WithMethod(http.MethodGet). WithPath("/v2.0/vpcs"). WithResponse(new(model.ListVpcsResponse)). WithContentType("application/json"). Build() ``` ### Response #### Success Response (200) - **response** (model.ListVpcsResponse) - An empty instance of the response type for deserialization. ``` -------------------------------- ### Create and Use VPC Client in Go Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README.md Demonstrates initializing a VPC client with region, authentication, and HTTP configurations, then making a request to list VPCs. Ensure the region is valid to avoid panics. ```go package main import ( "fmt" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/config" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/def" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2" vpcModel "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/model" vpcRegion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/region" ) func main() { // Replace with your actual AK, SK, and project ID auth := basic.NewCredentialsBuilder(). WithAk("YOUR_AK"). WithSk("YOUR_SK"). WithProjectId("YOUR_PROJECT_ID"). Build() // Configure HTTP settings (optional) httpConfig := config.DefaultHttpConfig() region, err := vpcRegion.SafeValueOf("cn-north-4") if err != nil { fmt.Println(err) return } // Create a service client hcClient, err := vpc.VpcClientBuilder(). // Configure region, it will cause a panic if the region does not exist WithRegion(region). // Configure authentication WithCredential(auth). // Configure HTTP WithHttpConfig(httpConfig). SafeBuild() if err != nil { fmt.Println(err) return } client := vpc.NewVpcClient(hcClient) // Create a request request := &vpcModel.ListVpcsRequest{} // Configure the number of records on each page limit := int32(1) request.Limit = &limit // Send the request and get the response response, err := client.ListVpcs(request) // Handle error and print response if err == nil { fmt.Printf("%+v\n", response) } else { fmt.Println(err) } } ``` -------------------------------- ### Configure Request Retries for VPC Service Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README_CN.md Configure maximum retries, retry conditions, and retry strategies for GET requests when encountering network exceptions or throttling. This example uses the VPC ListVpcs interface with a maximum of 3 retries. ```go package main import ( "fmt" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/invoker/retry" vpc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/model" "os" ) func main() { auth, err := basic.NewCredentialsBuilder(). WithAk(os.Getenv("HUAWEICLOUD_SDK_AK")), WithSk(os.Getenv("HUAWEICLOUD_SDK_SK")), WithProjectId("") SafeBuild() if err != nil { fmt.Println(err) return } // 初始化客户端 hcClient, err := vpc.VpcClientBuilder(). WithEndpoint("") WithCredential(auth). SafeBuild() if err != nil { fmt.Println(err) return } client := vpc.NewVpcClient(hcClient) // 初始化请求 request := &model.ListVpcsRequest{} // 发送请求,当请求异常时进行重试 response, err := client.ListVpcsInvoker(request).WithRetry(3, func(i interface{}, err error) bool { return err != nil }, new(retry.None)).Invoke() if err == nil { fmt.Printf("%+v\n", response) } else { fmt.Printf("%+v\n", err) } } ``` -------------------------------- ### Error Handling Pattern Example Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Demonstrates a common pattern for handling errors returned by SDK API calls. This involves checking the error returned from the API method and potentially inspecting the error details. ```go if err != nil { // Handle error } ``` -------------------------------- ### Upload and Download Files with DSC Service Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README_CN.md Example demonstrating how to upload a local image file for processing (e.g., adding a watermark) and then download the resulting file stream using the Data Security Center (DSC) service. ```go package main import ( "fmt" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/def" dsc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dsc/v1" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dsc/v1/model" "os" ) func createImageWatermark(client *dsc.DscClient) error { // 打开文件 file, err := os.Open("demo.jpg") if err != nil { return err } defer file.Close() body := &model.CreateImageWatermarkRequestBody{ File: def.NewFilePart(file), BlindWatermark: def.NewMultiPart("test123"), } request := &model.CreateImageWatermarkRequest{Body: body} response, err := client.CreateImageWatermark(request) if err != nil { return err } fmt.Printf("status code: %d\n", response.HttpStatusCode) // 下载文件 result, err := os.Create("result.jpg") if err != nil { return err } _, err = response.Consume(result) return err } func main() { ak := os.Getenv("HUAWEICLOUD_SDK_AK") sk := os.Getenv("HUAWEICLOUD_SDK_SK") endpoint := "{your endpoint string}" projectId := "{your project id}" credentials, err := basic.NewCredentialsBuilder(). WithAk(ak). WithSk(sk). WithProjectId(projectId). SafeBuild() if err != nil { fmt.Println(err) return } hcClient, err := dsc.DscClientBuilder(). WithEndpoint(endpoint). WithCredential(credentials). SafeBuild() if err != nil { fmt.Println(err) return } client := dsc.NewDscClient(hcClient) err = createImageWatermark(client) } ``` -------------------------------- ### Provider Chain (Auto) Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/authentication.md Instantiate a client without providing explicit credentials. The SDK will use the DefaultCredentialProviderChain to discover credentials from environment variables, profile files, or the metadata service. This example shows building a VPC client. ```go // No credential provided - uses DefaultCredentialProviderChain client, err := vpc.VpcClientBuilder(). WithRegion(region). SafeBuild() if err != nil { log.Fatal(err) // Will fail if no credential in env/file/metadata } ``` -------------------------------- ### WithIgnoreContentTypeForGetRequest Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/configuration.md Omits the Content-Type header for GET requests. This can be useful in specific scenarios where the server does not expect a Content-Type for GET requests. ```APIDOC ## WithIgnoreContentTypeForGetRequest ### Description Omits Content-Type header for GET requests. ### Method func (config *HttpConfig) WithIgnoreContentTypeForGetRequest(ignoreContentTypeForGetRequest bool) *HttpConfig ### Parameters #### Path Parameters - ignoreContentTypeForGetRequest (bool) - Required - true = skip Content-Type for GET ``` -------------------------------- ### Omit Content-Type Header for GET Requests Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/configuration.md When set to true, this option omits the Content-Type header for GET requests, which can be necessary for certain APIs. ```go func (config *HttpConfig) WithIgnoreContentTypeForGetRequest(ignoreContentTypeForGetRequest bool) *HttpConfig ``` -------------------------------- ### Example Endpoints Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/region-management.md Illustrative examples of service endpoints using common region IDs. These demonstrate how the general format is applied to specific services and regions. ```text https://vpc.cn-north-4.myhuaweicloud.com ``` ```text https://ecs.cn-north-4.myhuaweicloud.com ``` ```text https://rds.eu-west-0.myhuaweicloud.com ``` -------------------------------- ### Basic Credentials (Manual) Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/authentication.md Manually configure basic credentials with Access Key (AK), Secret Key (SK), and Project ID. Ensure to handle potential errors during the build process. ```go creds, err := basic.NewCredentialsBuilder(). WithAk("AKIAIOSFODNN7EXAMPLE"). WithSk("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"). WithProjectId("c1d2e3a4f5g6h7i8"). SafeBuild() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Initialize ECS Client Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/quick-start.md Demonstrates how to initialize an ECS client by specifying the region, credentials, and building the HTTP client. ```go import ( ecs "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v1" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v1/model" ecsRegion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v1/region" ) // Get region region, _ := ecsRegion.SafeValueOf("cn-north-4") // Create HTTP client hcClient, _ := ecs.EcsClientBuilder(). WithRegion(region). WithCredential(creds). SafeBuild() // Create service client ecsClient := ecs.NewEcsClient(hcClient) // Call API response, _ := ecsClient.ListServers(&model.ListServersRequest{}) ``` -------------------------------- ### Initialize VPC Client for Cloud Service Alliance Scenarios in Go Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README.md Demonstrates how to initialize the VPC client with a specific endpoint and basic credentials, suitable for Cloud Service Alliance scenarios. Ensure you provide your project ID. ```go package main import ( "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic" vpc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2" "os" ) func main() { // Specify the endpoint, take the endpoint of VPC service in region of eu-west-101 for example endpoint := "https://vpc.eu-west-101.myhuaweicloud.com" // Initialize the credentials, you should provide projectId or domainId in this way, take initializing BasicCredentials for example basicAuth, err := basic.NewCredentialsBuilder(). WithAk(os.Getenv("HUAWEICLOUD_SDK_AK")), WithSk(os.Getenv("HUAWEICLOUD_SDK_SK")), WithProjectId("{yourprojectId string}") SafeBuild() if err != nil { fmt.Println(err) return } // Initialize specified New{Service}Client, take initializing the regional service VPC's VpcClient for example hcClient, err := vpc.VpcClientBuilder(). WithEndpoint(endpoint). WithCredential(basicAuth). SafeBuild() if err != nil { fmt.Println(err) return } client := vpc.NewVpcClient(hcClient) } ``` -------------------------------- ### Catching RequestTimeoutError Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/errors.md Example of how to check if an error returned from an SDK call is a RequestTimeoutError. ```go response, err := client.ListVpcs(&model.ListVpcsRequest{}) if err != nil { if _, ok := err.(*sdkerr.RequestTimeoutError); ok { fmt.Println("Request timeout - increase timeout or check network") } } ``` -------------------------------- ### Initialize VPC Client with Default Configuration Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README.md Initializes the VPC client using default HTTP configurations. Ensure necessary imports are present. ```go import ( "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/config" vpc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2" ) // Use default configuration httpConfig := config.DefaultHttpConfig() hcClient, err := vpc.VpcClientBuilder(). WithHttpConfig(httpConfig). SafeBuild() if err != nil { // handle error } client := vpc.NewVpcClient(hcClient) ``` -------------------------------- ### Get VPC Details Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/quick-start.md Retrieves detailed information about a specific VPC using its ID. ```APIDOC ## Get VPC Details ### Description Retrieves detailed information for a specific VPC. ### Method `ShowVpc` ### Parameters #### Path Parameters - **VpcId** (string) - Required - The ID of the VPC to retrieve details for. ### Request Example ```go response, err := client.ShowVpc(&model.ShowVpcRequest{ VpcId: "vpc-123", }) ``` ### Response #### Success Response (200) - **Vpc** (model.Vpc) - Details of the VPC. - **Name** (string) - The name of the VPC. - **Cidr** (string) - The CIDR block of the VPC. ``` -------------------------------- ### Get Current Credential Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/core-http-client.md Retrieves the currently configured authentication credential instance from the client. ```go func (hc *HcHttpClient) GetCredential() auth.ICredential ``` -------------------------------- ### ListVpcPeerings Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/api-endpoints-reference.md Lists VPC peering connections. Supports GET requests to the /v2.0/vpc/peerings endpoint. ```APIDOC ## ListVpcPeerings ### Description Lists VPC peering connections. ### Method GET ### Endpoint /v2.0/vpc/peerings ``` -------------------------------- ### Create VPC Service Client Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/service-clients.md Demonstrates two methods for creating a VPC service client: using a service-specific builder or a generic service builder. Both require an initialized HTTP client, region, and credentials. ```go import ( "github.com/huaweicloud/huaweicloud-sdk-go-v3/core" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/region" ) // Method 1: Using service-specific builder hcClient, _ := core.NewHcHttpClientBuilder(). WithRegion(region). WithCredential(credentials). SafeBuild() vpcClient := v2.NewVpcClient(hcClient) // Method 2: Using service builder (shortcut) vpcClient, _ := v2.VpcClientBuilder(). WithRegion(region). WithCredential(credentials). SafeBuild() ``` -------------------------------- ### ListSecurityGroups Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/api-endpoints-reference.md Lists security groups in the project. Supports GET requests to the /v2.0/security-groups endpoint. ```APIDOC ## ListSecurityGroups ### Description Lists security groups in project. ### Method GET ### Endpoint /v2.0/security-groups ``` -------------------------------- ### Upload and Download Files with Go SDK Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README.md Demonstrates how to upload a file (e.g., an image for watermarking) and then download the processed file using the Data Security Center service. Ensure files are opened and closed properly, and handle potential errors during file operations and API calls. ```go package main import ( "fmt" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/def" dsc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dsc/v1" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dsc/v1/model" "os" ) func createImageWatermark(client *dsc.DscClient) error { // Open the file. file, err := os.Open("demo.jpg") if err != nil { return err } defer file.Close() body := &model.CreateImageWatermarkRequestBody{ File: def.NewFilePart(file), BlindWatermark: def.NewMultiPart("test123"), } request := &model.CreateImageWatermarkRequest{Body: body} response, err := client.CreateImageWatermark(request) if err != nil { return err } fmt.Printf("status code: %d\n", response.HttpStatusCode) // Download the file. result, err := os.Create("result.jpg") if err != nil { return err } _, err = response.Consume(result) return err } func main() { ak := os.Getenv("HUAWEICLOUD_SDK_AK") sk := os.Getenv("HUAWEICLOUD_SDK_SK") endpoint := "{your endpoint string}" projectId := "{your project id}" credentials, err := basic.NewCredentialsBuilder(). WithAk(ak). WithSk(sk). WithProjectId(projectId). SafeBuild() if err != nil { fmt.Println(err) return } hcClient, err := dsc.DscClientBuilder(). WithEndpoint(endpoint). WithCredential(credentials). SafeBuild() if err != nil { fmt.Println(err) return } client := dsc.NewDscClient(hcClient) err := createImageWatermark(client) } ``` -------------------------------- ### ListPorts Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/api-endpoints-reference.md Lists ports in the project. Supports GET requests to the /v1/{project_id}/ports endpoint. ```APIDOC ## ListPorts ### Description Lists ports in project. ### Method GET ### Endpoint /v1/{project_id}/ports ``` -------------------------------- ### Get Region Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/quick-start.md Obtain a region object from its string identifier. Handles unknown regions by returning an error. ```go r, err := region.SafeValueOf("cn-north-4") if err != nil { log.Fatalf("Unknown region: %v", err) } ``` -------------------------------- ### ListRouteTables Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/api-endpoints-reference.md Lists route tables in the project. Supports GET requests to the /v1/{project_id}/routetables endpoint. ```APIDOC ## ListRouteTables ### Description Lists route tables in project. ### Method GET ### Endpoint /v1/{project_id}/routetables ``` -------------------------------- ### Create Credentials from Environment Variables Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/quick-start.md Create SDK credentials using environment variables for Access Key (AK) and Secret Key (SK). This is the recommended approach for security. ```go creds, err := basic.NewCredentialsBuilder(). WithAk(os.Getenv("HUAWEICLOUD_SDK_AK")). WithSk(os.Getenv("HUAWEICLOUD_SDK_SK")). SafeBuild() if err != nil { log.Fatalf("Failed to create credentials: %v", err) } ``` -------------------------------- ### Create HttpRequestDefBuilder Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Initializes a new HttpRequestDefBuilder. Use this to start defining a new HTTP request definition. ```go func NewHttpRequestDefBuilder() *HttpRequestDefBuilder ``` -------------------------------- ### CreateVpc Operation Request Definition Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Example of generating an HttpRequestDef for the CreateVpc operation, which is a POST request to create a VPC. ```APIDOC ## CreateVpc Operation ### Description Generates the HTTP request definition for creating a VPC, including the request body. ### Method POST ### Endpoint /v2.0/vpcs ### Parameters #### Request Body - **Body** (interface{}) - Required - The request body for creating a VPC. ### Request Example ```go // Generated for CreateVpc operation GenReqDefForCreateVpc := def.NewHttpRequestDefBuilder(). WithMethod(http.MethodPost). WithPath("/v2.0/vpcs"). WithResponse(new(model.CreateVpcResponse)). WithContentType("application/json"). WithRequestField(def.NewFieldDef(). WithName("Body"). WithLocationType(def.Body)). Build() ``` ### Response #### Success Response (200) - **response** (model.CreateVpcResponse) - An empty instance of the response type for deserialization. ``` -------------------------------- ### NewFieldDef Constructor Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/request-response.md Creates a new FieldDef instance. Use this to start defining a field's HTTP mapping. ```go func NewFieldDef() *FieldDef ``` -------------------------------- ### Basic Credentials (Auto-discovery) Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/authentication.md Configure basic credentials using environment variables for AK and SK. The Project ID is auto-discovered during region binding. Handle build errors. ```go creds, err := basic.NewCredentialsBuilder(). WithAk(os.Getenv("HUAWEICLOUD_SDK_AK")). WithSk(os.Getenv("HUAWEICLOUD_SDK_SK")). // ProjectId auto-discovered during region binding SafeBuild() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Initialize Service Client with Specified Endpoint Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README.md Initialize a service client (e.g., VpcClient) with a specific endpoint and credentials. Requires setting AK, SK, and Project ID. ```go package main import ( "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/config" vpc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2" "os" ) func main() { // Specify the endpoint, take the endpoint of VPC service in region of cn-north-4 for example endpoint := "https://vpc.cn-north-4.myhuaweicloud.com" // Initialize the credentials, you should provide projectId or domainId in this way, take initializing BasicCredentials for example basicAuth, err := basic.NewCredentialsBuilder(). WithAk(os.Getenv("HUAWEICLOUD_SDK_AK")), WithSk(os.Getenv("HUAWEICLOUD_SDK_SK")), WithProjectId("{yourProjectId string}"), SafeBuild() if err != nil { fmt.Println(err) return } // Initialize specified New{Service}Client, take initializing the regional service VPC's VpcClient for example hcClient, err := vpc.VpcClientBuilder(). WithEndpoint(endpoint), WithCredential(basicAuth), WithHttpConfig(config.DefaultHttpConfig()), SafeBuild() if err != nil { fmt.Println(err) return } client := vpc.NewVpcClient(hcClient) } ``` -------------------------------- ### WithHost Method Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/configuration.md Sets the proxy hostname or IP address. Returns the Proxy instance for chaining. ```go func (p *Proxy) WithHost(host string) *Proxy ``` -------------------------------- ### Call API Method Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/service-clients.md Invoke an API method on the service client. This example demonstrates calling the ListVpcs method and handling the response. ```go response, err := vpcClient.ListVpcs(&vpc_model.ListVpcsRequest{}) if err == nil { fmt.Printf("Found %d VPCs\n", len(*response.Vpcs)) } ``` -------------------------------- ### Default Error Handler Structure Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/errors.md Defines the structure for the default error handler used by the SDK. No setup is required to use this handler. ```go type DefaultErrorHandler struct{} ``` -------------------------------- ### Custom Error Handler Implementation Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/errors.md An example implementation of a custom error handler that logs server errors before using the default error parsing. ```go type CustomErrorHandler struct{} func (h CustomErrorHandler) HandleError( req *request.DefaultHttpRequest, resp *response.DefaultHttpResponse) error { if resp.GetStatusCode() >= 500 { // Log server errors to monitoring system log.Printf("Server error: %d for %s %s", resp.GetStatusCode(), req.GetMethod(), req.GetUrl()) } // Use default error parsing return sdkerr.DefaultErrorHandler{}.HandleError(req, resp) } ``` -------------------------------- ### Service Client Synchronous Request Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/MANIFEST.txt Example of making a synchronous request using a service client. This pattern is suitable for simple, direct operations. ```go result, err := ecsClient.ListServers(ctx, &ecs.ListServersRequest{...}) ``` -------------------------------- ### Create a VPC Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/quick-start.md Demonstrates how to create a new Virtual Private Cloud (VPC) with a specified name and CIDR block. ```APIDOC ## Create a VPC ### Description Creates a new VPC with the specified name and CIDR block. ### Method `CreateVpc` ### Parameters #### Request Body - **Body** (model.CreateVpcRequestBody) - Required - The request body for creating a VPC. - **Vpc** (model.CreateVpcOption) - Required - VPC configuration. - **Name** (string) - Required - The name of the VPC. - **Cidr** (string) - Required - The CIDR block of the VPC. ### Request Example ```go response, err := client.CreateVpc(&model.CreateVpcRequest{ Body: &model.CreateVpcRequestBody{ Vpc: &model.CreateVpcOption{ Name: "my-vpc", Cidr: "10.0.0.0/16", }, }, }) ``` ### Response #### Success Response (200) - **Vpc** (model.Vpc) - Details of the created VPC. - **Id** (string) - The unique identifier of the VPC. ``` -------------------------------- ### Get VPC Details Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/quick-start.md Retrieve the details of a specific VPC using its ID. The response includes the VPC's name and CIDR block. ```go response, err := client.ShowVpc(&model.ShowVpcRequest{ VpcId: "vpc-123", }) if err == nil { fmt.Printf("VPC: %s\n", response.Vpc.Name) fmt.Printf("CIDR: %s\n", response.Vpc.Cidr) } ``` -------------------------------- ### Get AK/SK Credentials from Profile (Go) Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/README.md Retrieve AK/SK credentials using BasicCredentialProfileProvider or GlobalCredentialProfileProvider in Go. The profile file should be correctly configured. ```go import "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/provider" // basic basicProvider := provider.BasicCredentialProfileProvider() basicCred, err := basicProvider.GetCredentials() // global globalProvider := provider.GlobalCredentialProfileProvider() globalCred, err := globalProvider.GetCredentials() ``` -------------------------------- ### Build HTTP Client Source: https://github.com/huaweicloud/huaweicloud-sdk-go-v3/blob/master/_autodocs/quick-start.md Build an HTTP client for SDK requests, configuring it with the selected region and credentials. ```go httpClient, err := core.NewHcHttpClientBuilder(). WithRegion(r). WithCredential(creds). SafeBuild() if err != nil { log.Fatalf("Failed to build HTTP client: %v", err) } ```