Go

更新时间:
复制 MD 格式

This guide explains how to install and use the Go SDK for Alibaba Cloud Vision AI Open Platform, complete with code examples.

Note

For help with SDK integration, API usage, or other AI-related issues, join our Vision AI Open Platform support group on DingTalk (ID: 23109592).

This SDK requires Go 1.10.x or later. If your Go version is older, please upgrade it.

Prerequisites

Before using the Alibaba Cloud SDK, you must have an Alibaba Cloud account and an AccessKey. For more information, see Create an AccessKey.

Run the following commands to install the SDK package for the AI category you need.

  • Face and body: go get github.com/alibabacloud-go/facebody-20191230/v4

  • OCR: go get github.com/alibabacloud-go/ocr-20191230/v3

  • Commodity understanding: go get github.com/alibabacloud-go/goodstech-20191230/v2

  • Content moderation: go get github.com/alibabacloud-go/imageaudit-20191230/v3

  • Image recognition: go get github.com/alibabacloud-go/imagerecog-20190930/v2

  • Image enhancement: go get github.com/alibabacloud-go/imageenhan-20190930/v2

  • Image segmentation: go get github.com/alibabacloud-go/imageseg-20191230/v2

  • Object detection: go get github.com/alibabacloud-go/objectdet-20191230/v2

  • Image processing and analysis: go get github.com/alibabacloud-go/imageprocess-20200320/v2

  • Image search: go get github.com/alibabacloud-go/imgsearch-20200320/v2

  • Video enhancement: go get github.com/alibabacloud-go/videoenhan-20200320/v3

  • Video understanding: go get github.com/alibabacloud-go/videorecog-20200320/v2

  • Video segmentation: go get github.com/alibabacloud-go/videoseg-20200320/v2

  • Asynchronous task management: go get github.com/alibabacloud-go/viapi-20230117/v2

  • Face and body (server-side dedicated version 20200910): go get github.com/alibabacloud-go/facebody-20200910/v3

The SDKs are available at the following GitHub repositories:

AI category

GitHub link

Face and body

facebody-20191230

OCR

ocr-20191230

Commodity understanding

goodstech-20191230

Content moderation

imageaudit-20191230

Image recognition

imagerecog-20190930

Image enhancement

imageenhan-20190930

Image segmentation

imageseg-20191230

Object detection

objectdet-20191230

Image search

imgsearch-20200320

Image processing and analysis

imageprocess-20200320

Video enhancement

videoenhan-20200320

Video understanding

videorecog-20200320

Video segmentation

videoseg-20200320

Asynchronous task management

viapi-20230117

Face and body (server-side dedicated version 20200910)

facebody-20200910

Configure environment variables

Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Important
  • An Alibaba Cloud account has full access to all API operations. We recommend that you use a RAM user for API calls or routine O&M. For more information, see Create a RAM user.

  • Do not save your AccessKey ID or AccessKey Secret in project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.

  • Configure environment variables on Linux and macOS

    1. Open a terminal in IntelliJ IDEA.

    2. Run the following commands to configure the environment variables.

      Replace <access_key_id> with the AccessKey ID of your RAM user and <access_key_secret> with the AccessKey Secret of your RAM user. If you need to configure more permissions, see Control access permissions using a RAM policy.

      export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • Configure environment variables on Windows

    Create a new environment variable file, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared. Then, restart the Windows operating system. The following example uses Windows 10.

    1. Open File Explorer, right-click This PC, and then select Properties.

    2. In the left-side navigation pane, click Advanced system settings.

    3. On the Advanced tab of the System Properties dialog box, click Environment Variables.

    4. In the Environment Variables dialog box, click New.

    5. In the New System Variable dialog box, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.

    6. Restart the Windows operating system for the configurations to take effect.

SDK examples

This section uses the RecognizeBankCard operation as an example.

Process an OSS file in the Shanghai region

Note

For a list of endpoints and the features available in each region, see Endpoints.

package main

// We recommend using 'go mod tidy' to install dependencies.
import (
    "fmt"
    openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    // 1. Adapt this code for other services.
    //    This example uses the OCR service. To call a different service, such as image segmentation (SegmentCommonImage),
    //    you must change the imported packages and method names.
    //    - Find the correct package name (e.g., `imageseg20191230`) in the installation list above.
    //    - Find the operation name (e.g., `SegmentCommonImage`) in its API reference. For example, see the documentation for `SegmentCommonImage` at https://help.aliyun.com/document_detail/151960.html.
    //    - Update the import paths and method calls in this code accordingly.
    ocr20191230 "github.com/alibabacloud-go/ocr-20191230/v3/client"
    util "github.com/alibabacloud-go/tea-utils/v2/service"
    "github.com/alibabacloud-go/tea/tea"
)

func main() {
    // 2. Configure your credentials.
    //    For instructions on how to create an AccessKey, see https://help.aliyun.com/document_detail/175144.html.
    //    If you are using a RAM user's AccessKey, you must grant the RAM user the AliyunVIAPIFullAccess permission. For details, see https://help.aliyun.com/document_detail/145025.html.
    //    This example reads the AccessKey ID and Secret from environment variables.
    //    Set these environment variables before running the code.  
    accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")  
    accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    // Initialize the configuration object, which stores your credentials and endpoint.
	config := &openapi.Config{
		AccessKeyId: tea.String(accessKeyId),
		AccessKeySecret: tea.String(accessKeySecret),
	}
    // 3. Set the endpoint.
    //    You must change this to the endpoint for the correct service and region.
    //    For a list of endpoints, see https://help.aliyun.com/document_detail/143103.html.
    config.Endpoint = tea.String("ocr.cn-shanghai.aliyuncs.com")
    // 4. Create a client for the service.
    //    Replace with the client for the service you want to use.
    client, err := ocr20191230.NewClient(config)
    if err != nil {
        panic(err)
    }
    // 5. Create a request object.
    //    Replace with the request object for the operation you want to call.
    recognizeBankCardRequest := &ocr20191230.RecognizeBankCardRequest{
        ImageURL: tea.String("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg"),
    }
    runtime := &util.RuntimeOptions{}
    // 6. Call the service operation.
    //    The method name follows the pattern [OperationName]WithOptions.
    //    For example, the `SegmentCommonImage` operation corresponds to the method `SegmentCommonImageWithOptions`.
    recognizeBankCardResponse, err := client.RecognizeBankCardWithOptions(recognizeBankCardRequest, runtime)
    if err != nil {
        // Handle the error.
        fmt.Println(err.Error())
    } else {
        // Print the full response.
        fmt.Println(recognizeBankCardResponse)
        // Access a specific field from the response. This is just an example.
        // Refer to the API documentation for the structure of the response.
        fmt.Println(recognizeBankCardResponse.Body.Data.CardNumber)
    }
}
Note

To adapt this sample code for other services:

  1. When you import packages, you need to import the package for the corresponding category and the relevant classes. For the package name, refer to the SDK package name mentioned above. For the capability name, refer to the Action parameter in the corresponding API documentation.

    For example, if you want to use the general segmentation capability, the General Segmentation API documentation states that this capability belongs to the image segmentation category (imageseg20191230) and its name is SegmentCommonImage. You need to change ocr20191230 to imageseg20191230 and RecognizeBankCard to SegmentCommonImage in your code.

  2. The endpoint must match the service category. Otherwise, the InvalidAction.NotFound error is returned. For more information about endpoints, see Endpoints.

  3. Use the Client class from the correct service package.

  4. Use the Request and Response objects from the correct service package.

  5. The client method name corresponds to the API operation name. For example, the SegmentCommonImage operation is called using the SegmentCommonImageWithOptions method.

Process a local file or URL

Important

The main difference when processing a local file or a file from a URL is that you must use an ...AdvanceRequest object, and the file content is passed as a stream to the ImageURLObject parameter.

package main

// We recommend using 'go mod tidy' to install dependencies.
import (
    "fmt"
    openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    // 1. Adapt this code for other services.
    //    This example uses the OCR service. To call a different service, such as image segmentation (SegmentCommonImage),
    //    you must change the imported packages and method names.
    //    - Find the correct package name (e.g., `imageseg20191230`) in the installation list above.
    //    - Find the operation name (e.g., `SegmentCommonImage`) in its API reference. For example, see the documentation for `SegmentCommonImage` at https://help.aliyun.com/document_detail/151960.html.
    //    - Update the import paths and method calls in this code accordingly.
    ocr20191230 "github.com/alibabacloud-go/ocr-20191230/v3/client"
    util "github.com/alibabacloud-go/tea-utils/v2/service"
    "github.com/alibabacloud-go/tea/tea"
    "net/http"
)

func main() {
    // 2. Configure your credentials.
    //    For instructions on how to create an AccessKey, see https://help.aliyun.com/document_detail/175144.html.
    //    If you are using a RAM user's AccessKey, you must grant the RAM user the AliyunVIAPIFullAccess permission. For details, see https://help.aliyun.com/document_detail/145025.html.
    //    This example reads the AccessKey ID and Secret from environment variables.
    //    Set these environment variables before running the code.  
    accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")  
    accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    // Initialize the configuration object, which stores your credentials and endpoint.
	config := &openapi.Config{
		AccessKeyId: tea.String(accessKeyId),
		AccessKeySecret: tea.String(accessKeySecret),
	}
    // 3. Set the endpoint.
    //    You must change this to the endpoint for the correct service and region.
    //    For a list of endpoints, see https://help.aliyun.com/document_detail/143103.html.
    config.Endpoint = tea.String("ocr.cn-shanghai.aliyuncs.com")
    // 4. Create a client for the service.
    //    Replace with the client for the service you want to use.
    client, err := ocr20191230.NewClient(config)
    if err != nil {
        fmt.Print(err.Error())
        panic(err)
    }
    // Scenario 1: Use a local file
    //file, err:=os.Open("/tmp/bankCard.png")
    //if err != nil {
    //	fmt.Println("can not open file",err)
    //	panic(err)
    //}
    // Scenario 2: Use a file from any accessible URL
    httpClient := http.Client{}
    file, _ := httpClient.Get("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg")
    // 5. Create a request object for a stream.
    //    Replace with the request object for the operation you want to call.
    recognizeBankCardAdvanceRequest := &ocr20191230.RecognizeBankCardAdvanceRequest{
        ImageURLObject: file.Body,
    }
    runtime := &util.RuntimeOptions{}
    // 6. Call the service operation for a stream.
    //    For streams, the method name follows the pattern [OperationName]Advance.
    //    For example, the `SegmentCommonImage` operation corresponds to the method `SegmentCommonImageAdvance`.
    recognizeBankCardResponse, err := client.RecognizeBankCardAdvance(recognizeBankCardAdvanceRequest, runtime)
    if err != nil {
        // Handle the error.
        fmt.Println(err.Error())
    } else {
        // Print the full response.
        fmt.Println(recognizeBankCardResponse)
        // Access a specific field from the response. This is just an example.
        // Refer to the API documentation for the structure of the response.
        fmt.Println(recognizeBankCardResponse.Body.Data.CardNumber)
    }
}
Note

To adapt this sample code for other services:

  1. When you import packages, you need to import the packages and related classes for the corresponding category. For package names, refer to the SDK package names mentioned above, and for capability names, refer to the Action parameter in the corresponding API documentation.

    For example, if you want to use the general segmentation capability, you can learn from the General Segmentation API documentation that this capability belongs to the image segmentation category (imageseg20191230) and its name is SegmentCommonImage, which requires you to change ocr20191230 to imageseg20191230 and RecognizeBankCard to SegmentCommonImage in your code.

  2. You must specify the endpoint for the corresponding category. If the endpoint category does not match, an InvalidAction.NotFound error is reported. For more information about endpoints, see Endpoints.

  3. Use the Client class from the correct service package.

  4. Use the Request and Response objects from the correct service package.

  5. The client method name corresponds to the operation name, with an Advance suffix for stream-based requests. For example, the SegmentCommonImage operation is called using the SegmentCommonImageAdvance method.

FAQ

Handling API call failures

If an API call fails, first, upgrade the SDK package to the latest version, which can be found at the GitHub links listed above. If your project uses multiple service packages, upgrade all of them to prevent conflicts.

Finding the correct dependency version

Search for the operation name in the OpenAPI Portal. Select the API from the Vision AI Open Platform category, and then view the generated Go sample code.

Installing dependencies

After writing your code, run go mod tidy to install the required dependencies.

Technical support

If the issue persists, join the Vision AI Open Platform support group on DingTalk (ID: 23109592) for technical assistance.