All Products
Search
Document Center

Alibaba Cloud SDK:Use the Alibaba Cloud Go SDK with an IDE

Last Updated:Jun 02, 2026

Get started with the Alibaba Cloud Go SDK using Visual Studio Code (VS Code) on Windows.

Prerequisites

Use the SDK

Use the sample project from OpenAPI Explorer

Note

The sample project download may fail. If so, Use the SDK in an existing project instead.

  1. Go to the API Debugging page in the OpenAPI Portal. Select a cloud product and an API. This topic uses the DescribeRegions API of Elastic Computing Service (ECS) as an example. Enter DescribeRegions in the search bar. In the search results, click the API name to go to the API debugging page.

    1716346246233_4A41CC11-FA46-4973-BC7B-C4AAD6E7F3F0

  2. On the Parameter Settings tab, enter the required parameters. For reference, see the Document tab on the right. This tab provides the API description, notes, and billing information. It also explains the meaning and usage of each parameter.

    The DescribeRegions API supports the following three parameters:

    Parameter name

    Required

    Description

    InstanceChargeType

    Optional

    The supported regions may vary based on the instance billing method. The default value is PrePaid.

    ResourceType

    Optional

    The supported regions may vary based on the resource type. The default value is instance.

    AcceptLanguage

    Optional

    The language of the returned results. The default value is zh-CN.

    1716346635851_0B018C7F-D759-497b-B529-58E23E4AC41B

  3. On the SDK Sample tab on the right, select a language. Click the Download Project button to download the complete SDK project to your local computer and decompress it.

    image

  4. In VS Code, click File > Open Folder and select the decompressed folder.

  5. Click Terminal > New Terminal to open a terminal at the bottom.

    image

  6. Run the following command to update module dependencies.

    go mod tidy
  7. Run the following command to execute the sample code in the main package.

    go run ./main
  8. Verify the result. In the Terminal, press Ctrl+F and search for statusCode. If the output contains "statusCode": 200, the API call is successful.

    image

Use the SDK in an existing project

  1. In VS Code, click File > Open Folder and create or select a project folder, such as `gosdkproject`.

  2. Click Terminal > New Terminal, then run go mod init gosdkprojects to initialize the Go project.

    image

  3. Obtain the SDK.

    In SDK Center, select a cloud product such as ECS, set SDK Version to V2.0, and set Language to Go.

    image

  4. Install the SDK.

    Copy the installation command into the terminal and run it.

    image

  5. Create a .go file. Next to the project name, click New File... and enter a file name, such as `ecsDescribeRegions.go`.

    image

  6. Initialize the client.

    Initialize the ECS client before calling any ECS API.

    Important
    1. You must use an AccessKey for identity verification when you initialize the client. For information about how to obtain an AccessKey, see Create an AccessKey.

    2. After you obtain the AccessKey for the RAM user, you must set the AccessKey in the environment variables. For more information, see Configure environment variables on Linux, macOS, and Windows systems.

    3. For information about how to set the endpoint, see Endpoints.

    package main
    
    import (
    	"os"
    
    	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v4/client"
    	"github.com/alibabacloud-go/tea/tea"
    )
    
    // CreateClient initializes and returns an ECS client.
    // This function does not accept parameters, but requires that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set.
    // return *ecs20140526.Client
    // return error: Returns a non-nil error object if any error occurs during client creation.
    func CreateClient() (_result *ecs20140526.Client, _err error) {
        // Initialize the openapi.Config object to configure the ECS client.
        config := &openapi.Config{
            AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
            AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
            Endpoint:        tea.String("ecs.cn-hangzhou.aliyuncs.com"),
        }
        // Create and return an ECS client instance using the configuration.
        return ecs20140526.NewClient(config)
    }
    
  7. Call the API. Before you call an OpenAPI, review the API details. For more information, see API Documentation. This topic uses the `DescribeRegions` API of ECS as an example.

    Note

    Each API has a separate request object that follows the `${APIName}${Request}` naming convention, such as `DescribeRegionsRequest`.

    package main
    
    import (
    	"os"
    
    	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v4/client"
    	"github.com/alibabacloud-go/tea/tea"
    )
    
    // CreateClient initializes and returns an ECS client.
    // This function does not accept parameters, but requires that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set.
    // return *ecs20140526.Client
    // return error: Returns a non-nil error object if any error occurs during client creation.
    func CreateClient() (_result *ecs20140526.Client, _err error) {
    	// Initialize the openapi.Config object to configure the ECS client.
    	config := &openapi.Config{
    		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
    		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
    		Endpoint:        tea.String("ecs.cn-hangzhou.aliyuncs.com"),
    	}
    	// Create and return an ECS client instance using the configuration.
    	return ecs20140526.NewClient(config)
    }
    
    // The InvokeApi function calls the DescribeRegions API of ECS to query available region information.
    //
    // Return values:
    // _result: Returns a pointer of the *ecs20140526.DescribeRegionsResponse type, which contains the queried region information.
    // _err: Returns an error message of the error type. This value is not empty if an error occurs during the call.
    func InvokeApi()(_result *ecs20140526.DescribeRegionsResponse, _err error) {
    	// Create an ECS client.
    	client, _err := CreateClient()
    	if _err != nil {
    		// If an error occurs during client creation, return the error message directly.
    		return _result, _err
    	}
    
    	// Create a DescribeRegions request.
    	describeRegionsRequest := &ecs20140526.DescribeRegionsRequest{}
    	// Initiate the DescribeRegions request and return the result.
    	return client.DescribeRegions(describeRegionsRequest)
    }
    
  8. Handle exceptions.

    The Alibaba Cloud Go SDK returns errors for standard exception handling (Exception handling). For unexpected situations, use panic with defer and recover. panic stops execution immediately. Within a defer block, recover catches the panic and resumes normal execution.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v4/client"
    	"github.com/alibabacloud-go/tea/tea"
    )
    
    // CreateClient initializes and returns an ECS client.
    // This function does not accept parameters, but requires that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set.
    // return *ecs20140526.Client
    // return error: Returns a non-nil error object if any error occurs during client creation.
    func CreateClient() (_result *ecs20140526.Client, _err error) {
    	// Initialize the openapi.Config object to configure the ECS client.
    	config := &openapi.Config{
    		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
    		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
    		Endpoint:        tea.String("ecs.cn-hangzhou.aliyuncs.com"),
    	}
    	// Create and return an ECS client instance using the configuration.
    	return ecs20140526.NewClient(config)
    }
    
    // The InvokeApi function calls the DescribeRegions API of ECS to query available region information.
    //
    // Return values:
    // _result: Returns a pointer of the *ecs20140526.DescribeRegionsResponse type, which contains the queried region information.
    // _err: Returns an error message of the error type. This value is not empty if an error occurs during the call.
    func InvokeApi() (_result *ecs20140526.DescribeRegionsResponse, _err error) {
    	// Create an ECS client.
    	client, _err := CreateClient()
    	if _err != nil {
    		// If an error occurs during client creation, return the error message directly.
    		return _result, _err
    	}
    
    	// Create a DescribeRegions request.
    	describeRegionsRequest := &ecs20140526.DescribeRegionsRequest{}
    	// Initiate the DescribeRegions request and return the result.
    	return client.DescribeRegions(describeRegionsRequest)
    }
    
    // This function obtains region information by calling an API, and recovers from and handles exceptions when they occur.
    func main() {
    	// Use defer only in scenarios such as deep recursion or unexpected errors.
    	defer func() {
    		if err := tea.Recover(recover()); err != nil {
    			// When an exception is caught, handle it based on the exception type.
    			if sdkError, ok := err.(*tea.SDKError); ok {
    				// Print the SDK error message, error code, and related data.
    				fmt.Println(tea.StringValue(sdkError.Message))
    				fmt.Println(tea.StringValue(sdkError.Code))
    				fmt.Println(tea.StringValue(sdkError.Data))
    			} else {
    				// Print other types of error messages.
    				fmt.Println(err)
    			}
    		}
    	}()
    	// Call the API to get the result.
    	result, _ := InvokeApi()
    	// Traverse and print the region information in the result.
    	for _, region := range result.Body.Regions.Region {
    		fmt.Println("regionId: " + tea.StringValue(region.RegionId))
    	}
    	// Print the RequestId.
    	fmt.Println("RequestId: " + tea.StringValue(result.Body.RequestId))
    }
    
  9. In the terminal, run go run to execute the code.

    image

References

Advanced documentation