This topic describes how to use Alibaba Cloud Image Search SDKs for Go.

Preparations

  • Before you install and use Alibaba Cloud SDKs, make sure that you have created an Alibaba Cloud account and obtained an AccessKey pair. For more information, see Create an AccessKey pair.
  • Install the Alibaba Cloud SDK for Go. The Alibaba Cloud SDK for Go supports Go 1.7 or later. You can install the Alibaba Cloud SDK for Go by using the following methods:
    • (Recommended) Use Glide.
      Run the following command to install the Alibaba Cloud SDK for Go:
      glide get github.com/aliyun/alibaba-cloud-sdk-go
    • Use govendor.
      Run the following command to install the Alibaba Cloud SDK for Go:
      go get -u github.com/aliyun/alibaba-cloud-sdk-go/sdk

Sample code

The following complete sample code is provided:

package main
import (
    "encoding/base64"
    "fmt"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints"
    "github.com/aliyun/alibaba-cloud-sdk-go/services/imagesearch"
    "io/ioutil"
)
func main() {
    endpoints.AddEndpointMapping("<region>", "ImageSearch", "imagesearch.<region>.aliyuncs.com")
    // Create a client instance.
    client, err := imagesearch.NewClientWithAccessKey(
        "<region>",         // The region ID.
        "<your-access-key-id>",         // Your AccessKey ID.
        "<your-access-key-secret>");    // Your AccessKey secret.
    if err ! = nil {
        // Handle exceptions.
        panic(err)
    }
    // Delete the image.
    deleteRequest := imagesearch.CreateDeleteImageRequest()
    deleteRequest.InstanceName = "demo"
    deleteRequest.PicName = "test"
    deleteRequest.ProductId = "test"
    deleteResponse, err := client.DeleteImage(deleteRequest)
    if err ! = nil {
        panic(err)
    }
    fmt.Println(deleteResponse)
    // Add the image.
    addRequest := imagesearch.CreateAddImageRequest()
    addRequest.InstanceName = "demo"
    addRequest.PicName = "test"
    addRequest.ProductId = "test"
    b, err := ioutil.ReadFile("/home/admin/demo.jpg")
    if err ! = nil {
        panic(err)
    }
    messageBody := base64.StdEncoding.EncodeToString(b)
    addRequest.PicContent = messageBody
    addResponse, err := client.AddImage(addRequest)
    if err ! = nil {
         panic(err)
    }
    fmt.Println(addResponse)
    // Search for images.
    searchRequest := imagesearch.CreateSearchImageRequest()
    searchRequest.InstanceName = "demo"
    searchRequest.PicName = "test"
    searchRequest.ProductId = "test"
    searchRequest.Type = "SearchByName"
    searchResponse, err := client.SearchImage(searchRequest)
    if err ! = nil {
        // Handle exceptions.
        panic(err)
    }
    fmt.Println(searchResponse)
}