全部产品
云市场

Go SDK

更新时间:2019-04-11 14:50:44

准备工作

  1. 在安装和使用阿里云SDK前,确保您已经注册阿里云账号并生成访问访问密钥(AccessKey)。详情参考创建AccessKey
  2. 安装Go SDK。阿里云Go SDK支持Go 1.7及以上版本,您可以通过以下方式安装Go SDK:
    • 使用Glide安装GO SDK(推荐)。
      执行以下命令,安装阿里云Go SDK:
      1. glide get github.com/aliyun/alibaba-cloud-sdk-go
    • 使用Govendor安装。
      执行以下命令,安装阿里云Go SDK:
      1. go get -u github.com/aliyun/alibaba-cloud-sdk-go/sdk

完整代码示例

  1. package main
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints"
  6. "github.com/aliyun/alibaba-cloud-sdk-go/services/imagesearch"
  7. "io/ioutil"
  8. )
  9. func main() {
  10. endpoints.AddEndpointMapping("<region>", "ImageSearch", "imagesearch.<region>.aliyuncs.com")
  11. // 创建client实例
  12. client, err := imagesearch.NewClientWithAccessKey(
  13. "<region>", // 您的可用区ID
  14. "<your-access-key-id>", // 您的Access Key ID
  15. "<your-access-key-secret>") // 您的Access Key Secret
  16. if err != nil {
  17. // 异常处理
  18. panic(err)
  19. }
  20. // 删除图片
  21. deleteRequest := imagesearch.CreateDeleteImageRequest()
  22. deleteRequest.InstanceName = "demo"
  23. deleteRequest.PicName = "test"
  24. deleteRequest.ProductId = "test"
  25. deleteResponse, err := client.DeleteImage(deleteRequest)
  26. if err != nil {
  27. panic(err)
  28. }
  29. fmt.Println(deleteResponse)
  30. // 添加图片
  31. addRequest := imagesearch.CreateAddImageRequest()
  32. addRequest.InstanceName = "demo"
  33. addRequest.PicName = "test"
  34. addRequest.ProductId = "test"
  35. b, err := ioutil.ReadFile("/home/admin/demo.jpg")
  36. if err != nil {
  37. panic(err)
  38. }
  39. messageBody := base64.StdEncoding.EncodeToString(b)
  40. addRequest.PicContent = messageBody
  41. addResponse, err := client.AddImage(addRequest)
  42. if err != nil {
  43. panic(err)
  44. }
  45. fmt.Println(addResponse)
  46. // 查询图片
  47. searchRequest := imagesearch.CreateSearchImageRequest()
  48. searchRequest.InstanceName = "demo"
  49. searchRequest.PicName = "test"
  50. searchRequest.ProductId = "test"
  51. searchRequest.Type = "SearchByName"
  52. searchResponse, err := client.SearchImage(searchRequest)
  53. if err != nil {
  54. // 异常处理
  55. panic(err)
  56. }
  57. fmt.Println(searchResponse)
  58. }