All Products
Search
Document Center

IoT Platform:Use IoT Platform SDK for Go

Last Updated:Mar 07, 2024

IoT Platform provides an SDK for Go. This topic describes how to install and configure IoT Platform SDK for Go. This topic also provides sample codes on how to use the SDK to call API operations of IoT Platform.

Install IoT Platform SDK for Go

  1. Install Go.

    The SDK for Go requires Go 1.13.0 or later. Download a Go installation package from the official Go website and install Go.

  2. After Go is installed, create a system variable named GOPATH and set the value to your code directory.

    To obtain more information about the GOPATH variable, run the go help gopath command.

  3. Run the following command to install Alibaba Cloud SDK for Go. Use go mod commands to manage dependencies.

    Note

    • By default, the following command is run to install the latest SDK. If you want to install a specific version of the SDK, add the version number to the end of the command, such as @v3.0.0. For information about the historical versions of SDKs for Go, see SDK Code.

      For more information about IoT Platform SDK for Go, visit alibabacloud-go-sdk.

    • By default, IoT Platform SDK for Go is installed in the $GOPATH/src/github.com/alibabacloud-go/iot-20180120 directory. You can run the go env GOPATH command to obtain the value of $GOPATH.

      If a dependency does not exist in IoT Platform SDK for Go, run the go mod tidy command to pull dependencies.

    go get github.com/alibabacloud-go/iot-20180120/v6

Initialize IoT Platform SDK for Go

  1. Create the config object to store SDK initialization information, such as the AccessKey ID, AccessKey secret, and region ID.

  2. Call the iot.NewClient(config) method to load the SDK information and create a client instance. Then, the SDK is initialized.

For example, if you want to use the SDK in the China (Shanghai) region, you can use the following code to initialize the SDK. In the production environment, you must select the region where IoT Platform is activated.

import (
  "encoding/json"
  "strings"
  "fmt"
  "os"
  iot20180120  "github.com/alibabacloud-go/iot-20180120/v6/client"
  openapi  "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  util  "github.com/alibabacloud-go/tea-utils/v2/service"
  "github.com/alibabacloud-go/tea/tea"
)


/**
 * Initialize the Client with the AccessKey of the account
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func CreateClient (accessKeyId *string, accessKeySecret *string) (_result *iot20180120.Client, _err error) {
  config := &openapi.Config{
    // Required, your AccessKey ID
    AccessKeyId: accessKeyId,
    // Required, your AccessKey secret
    AccessKeySecret: accessKeySecret,
  }
  // See https://api.alibabacloud.com/product/Iot.
  config.Endpoint = tea.String("iot.cn-beijing.aliyuncs.com")
  _result = &iot20180120.Client{}
  _result, _err = iot20180120.NewClient(config)
  return _result, _err
}

func _main (args []*string) (_err error) {
  // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
  // The project code leakage may result in the leakage of AccessKey, posing a threat to the security of all resources under the account. The following code example is called by using the environment variable to obtain the AccessKey, for reference only. It is recommended to use the more secure STS credential. For more credentials, please refer to: https://www.alibabacloud.com/help/en/alibaba-cloud-sdk-262060/latest/configure-credentials-378661
  client, _err := CreateClient(tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")), tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")))
  if _err != nil {
    return _err
  }

Parameter

Description

accessKeyId

The AccessKey ID of your Alibaba Cloud account.

You can go to the AccessKey Pair page in the Alibaba Cloud Management Console to create or view your AccessKey pairs.

accessKeySecret

The AccessKey secret of your Alibaba Cloud account.

RegionId

The ID of the region where your IoT Platform instance resides. The region ID is used in the endpoint for service access. The endpoint is in the iot.${RegionId}.aliyuncs.com format.

You can view the region in the upper-left corner of the IoT Platform console.

For more information about the formats of region IDs, see Supported regions.

Initiate a request

The SDK encapsulates two classes for each API operation. The class whose name is in the ${API name}+"Request" format indicates the request, and the class whose name is in the ${API name}+"Response" format indicates the response.

Procedure

  1. Initialize the SDK. For more information, see Initialize the SDK.

  2. Create an API request by generating a request instance whose class name is in the ${API name}+"Request" format.

  3. Call the request.${Request parameter} method of the request instance to specify the request parameters.

  4. Create a response instance whose class name is in the ${API name}+"Response" format to obtain the response. Call the ${API name}(request) method of the client instance to obtain the response to the API request. The response includes the body and the headers that are returned by the server.

For more information about the API operations of IoT Platform, see List of operations by function. For more information about the request parameters and response parameters of each API operation, see the API reference.

The following example shows how to call the Pub operation to publish a message to a topic. For more information about request parameters, see Pub.

Important

In the following sample code, ${iotInstanceId} specifies the ID of an instance. You can view the ID of the instance on the Overview page in the IoT Platform console.

  • If your instance has an ID, you must specify the ID for this parameter. Otherwise, the call fails.

  • If no Overview page or ID is generated for your instance, you do not need to configure this parameter. You must delete the request code that is related to the IotInstanceId parameter or specify an empty string ("") for the parameter. Otherwise, the call fails.

For more information about IoT Platform instances, see Overview. For more information about how to purchase an instance, see Purchase Enterprise Edition instances. For more information, see FAQ about IoT Platform instances.

  pubRequest := &iot20180120.PubRequest{
    ProductKey: tea.String("${productKey}"),
    IotInstanceId: tea.String("${iotInstanceId}"),
    TopicFullName: tea.String("/${productKey}/${deviceName}/user/get"),
    MessageContent: tea.String("eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0="),
  }
  runtime := &util.RuntimeOptions{}
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    // Copy the code to run, please print the return value of the API by yourself.
    _, _err = client.PubWithOptions(pubRequest, runtime)
    if _err != nil {
      return _err
    }

    return nil
  }()

Complete sample code

Note

You can replace the values of the preceding parameters with actual values based on your business scenario.

// This file is auto-generated, don't edit it. Thanks.
package main

import (
  "encoding/json"
  "strings"
  "fmt"
  "os"
  iot20180120  "github.com/alibabacloud-go/iot-20180120/v6/client"
  openapi  "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  util  "github.com/alibabacloud-go/tea-utils/v2/service"
  "github.com/alibabacloud-go/tea/tea"
)


/**
 * Initialize the Client with the AccessKey of the account
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func CreateClient (accessKeyId *string, accessKeySecret *string) (_result *iot20180120.Client, _err error) {
  config := &openapi.Config{
    // Required, your AccessKey ID
    AccessKeyId: accessKeyId,
    // Required, your AccessKey secret
    AccessKeySecret: accessKeySecret,
  }
  // See https://api.alibabacloud.com/product/Iot.
  config.Endpoint = tea.String("iot.cn-beijing.aliyuncs.com")
  _result = &iot20180120.Client{}
  _result, _err = iot20180120.NewClient(config)
  return _result, _err
}

func _main (args []*string) (_err error) {
  // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
  // The project code leakage may result in the leakage of AccessKey, posing a threat to the security of all resources under the account. The following code example is called by using the environment variable to obtain the AccessKey, for reference only. It is recommended to use the more secure STS credential. For more credentials, please refer to: https://www.alibabacloud.com/help/en/alibaba-cloud-sdk-262060/latest/configure-credentials-378661
  client, _err := CreateClient(tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")), tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")))
  if _err != nil {
    return _err
  }

  pubRequest := &iot20180120.PubRequest{
    ProductKey: tea.String("${productKey}"),
    IotInstanceId: tea.String("${iotInstanceId}"),
    TopicFullName: tea.String("/${productKey}/${deviceName}/user/get"),
    MessageContent: tea.String("eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0="),
  }
  runtime := &util.RuntimeOptions{}
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    // Copy the code to run, please print the return value of the API by yourself.
    _, _err = client.PubWithOptions(pubRequest, runtime)
    if _err != nil {
      return _err
    }

    return nil
  }()

  if tryErr != nil {
    var error = &tea.SDKError{}
    if _t, ok := tryErr.(*tea.SDKError); ok {
      error = _t
    } else {
      error.Message = tea.String(tryErr.Error())
    }
    // Only a printing example. Please be careful about exception handling and do not ignore exceptions directly in engineering projects.
    // print error message
    fmt.Println(tea.StringValue(error.Message))
    // Please click on the link below for diagnosis.
    var data interface{}
    d := json.NewDecoder(strings.NewReader(tea.StringValue(error.Data)))
    d.Decode(&data)
    if m, ok := data.(map[string]interface{}); ok {
      recommend, _ := m["Recommend"]
      fmt.Println(recommend)
    }
    _, _err = util.AssertAsString(error.Message)
    if _err != nil {
      return _err
    }
  }
  return _err
}


func main() {
  err := _main(tea.StringSlice(os.Args[1:]))
  if err != nil {
    panic(err)
  }
}

Appendix: Sample code

You can view or download the sample code of API operations in IoT Platform SDK Sample Center. Sample code of SDKs for Java, Python, PHP, Node.js, Go, C++, and .NET is provided.

Alibaba Cloud OpenAPI Explorer provides online debugging tools for API operations. On the API Debugging page, you can search for API operations, call API operations, and generate sample code for API operations of different SDKs. On the right side of the page, you can view the sample code of an SDK on the Sample Code tab. On the Debugging Result tab, you can view the actual request URL and response in the JSON format.