Go SDK instructions
IoT Platform provides a server-side SDK for Go. You can install and configure the Go SDK to call IoT Platform cloud APIs from your server-side applications.
Install the SDK
-
Install the Go development environment.
The SDK supports Go 1.13.0 or later. Visit the official Go website to download it.
-
After installing Go, create the GOPATH system variable and point it to your code directory.
To learn more about GOPATH, run the
go help gopathcommand. -
Run the following command to install the Alibaba Cloud Go SDK and use Go modules to manage project dependencies.
Important-
The SDK version in the following command is only an example. For the latest version, see SDK installation method for IoT Platform in OpenAPI Portal. For the version history of the Go SDK, see SDK Code.
For more information about the Go SDK, visit alibabacloud-go-sdk.
-
The Go SDK is installed in the $GOPATH/src/github.com/alibabacloud-go/iot-20180120 directory by default. To view the GOPATH, run the
go env GOPATHcommand.If a dependency package is missing, run the
go mod tidycommand to download it.
go get github.com/alibabacloud-go/iot-20180120/v6 -
Initialize the SDK
-
Create a config object to store SDK initialization information, including the AccessKey ID, AccessKey secret, and region ID.
-
Call the
iot.NewClient(config)method to create a client instance and complete SDK client initialization.
The following code provides an example of how to initialize the SDK for the China (Shanghai) region. In your actual scenario, replace the endpoint with the one for the region where your IoT Platform service is located.
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"
)
/**
* Use an AccessKey pair (AccessKey ID and AccessKey secret) to initialize a client.
* @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,
}
// For more information about the endpoint, see https://api.aliyun.com/product/Iot.
config.Endpoint = tea.String("iot.cn-shanghai.aliyuncs.com")
_result = &iot20180120.Client{}
_result, _err = iot20180120.NewClient(config)
return _result, _err
}
func _main (args []*string) (_err error) {
// Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set in your code execution environment.
// Leaking the project code may cause the AccessKey pair to be leaked and threaten the security of all resources in your account. The following code provides an example of how to call the API using environment variables to obtain the AccessKey pair. This method is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS).
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 create or view your AccessKey pair on the AccessKey Management page of the Alibaba Cloud console. |
|
accessKeySecret |
The AccessKey secret of your Alibaba Cloud account. |
|
RegionId |
The region ID of your IoT Platform service. This is used to construct the service endpoint in the format: iot.${RegionId}.aliyuncs.com. You can view the current service region in the upper-left corner of the IoT Platform console. For more information about how to specify a region ID, see Regions and zones. |
For information about configuring the SDK client, including its HTTP request configuration, proxy configuration, timeout mechanism, and retry mechanism, see V2.0 Go SDK (Recommended).
To avoid security risks from hard-coding an AccessKey pair in your business code, manage the AccessKey pair by using environment variables.
Add the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to your local operating system, and set them to your AccessKey ID and AccessKey secret.
You can retrieve the AccessKey pair from your code by using the following methods:
-
os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") -
os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
For more authentication methods, see Managing access credentials.
Make a call
The IoT Platform cloud SDK encapsulates two classes for each API: ${API name}+"Request" and ${API name}+"Response". These classes contain the API request and response.
Steps
-
Initialize the SDK client. For more information, see Initialize the SDK.
-
Create a request for the API call to generate a request object instance of the
${API_Name}+"Request"class. -
Use the request object instance to call the
request.${Request_Parameter_Name}method and set the required request parameters for the API. -
Create a response object instance of the
${API_Name}+"Response"class to store the response. Use the client object instance to call the${API_Name}(request)method and obtain the API response. The response includes the body and headers from the server.
For more information about IoT Platform cloud APIs, see API list. For descriptions of the request parameters in the request and the response parameters in the response, see the documentation for the specific API.
This topic uses the Pub API as an example to show how to publish a message to a topic. For information about request parameters, see Pub.
In the following code, iotInstanceId is the instance ID. For more information about instances, see Instance overview.
For information about how to purchase an instance, see Purchase an Enterprise instance.
For information about how to obtain an instance ID, see IoT Platform instance-related FAQ.
pubRequest := &iot20180120.PubRequest{
ProductKey: tea.String("${productKey}"),
IotInstanceId: tea.String("${iotInstanceId}"),
DeviceName: tea.String("${deviceName}"),
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
}
}()
resp, _err := client.PubWithOptions(pubRequest, runtime)
if _err != nil {
return _err
}
console.Log(util.ToJSONString(resp))
return nil
}()
Complete code example
In your actual scenario, replace the parameter values based on the parameter descriptions provided earlier in this topic.
// 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"
)
/**
* Use an AccessKey pair (AccessKey ID and AccessKey secret) to initialize a client.
* @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,
}
// For more information about the endpoint, see https://api.aliyun.com/product/Iot.
config.Endpoint = tea.String("iot.cn-shanghai.aliyuncs.com")
_result = &iot20180120.Client{}
_result, _err = iot20180120.NewClient(config)
return _result, _err
}
func _main (args []*string) (_err error) {
// Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set in your code execution environment.
// Leaking the project code may cause the AccessKey pair to be leaked and threaten the security of all resources in your account. The following code provides an example of how to call the API using environment variables to obtain the AccessKey pair. This method is for reference only. We recommend that you use a more secure method, such as STS.
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{
// The ProductKey of the product.
ProductKey: tea.String("${productKey}"),
// The ID of the IoT Platform instance.
IotInstanceId: tea.String("${iotInstanceId}"),
DeviceName: tea.String("${deviceName}"),
// The custom topic of the device that receives the message.
TopicFullName: tea.String("/${productKey}/${deviceName}/user/get"),
// The message body to send: {"test":"task pub broadcast"}
MessageContent: tea.String("eyJ0ZXN0IjoidGFzayBwdWIgYnJvYWRjYXN0In0="),
}
runtime := &util.RuntimeOptions{}
tryErr := func()(_e error) {
defer func() {
if r := tea.Recover(recover()); r != nil {
_e = r
}
}()
// If you copy the code to run, print the return value of the API call.
_, _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())
}
// The following code is for demonstration purposes only. Handle exceptions with caution. Do not ignore exceptions in your project.
// Error message
fmt.Println(tea.StringValue(error.Message))
// Diagnosis address
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 go to the IoT Platform Cloud SDK Example Center to view or download sample code for API calls. The sample code includes examples for SDKs in languages such as Java, Python, PHP, Node.js, Go, C++, and .NET.
The Alibaba Cloud OpenAPI Developer Portal provides an online API debugging tool. On the API debugging page, you can quickly search for and test API calls. The system automatically generates sample SDK code for different languages based on the parameters that you enter. The sample code is displayed on the SDK Example tab on the right side of the page. On the Call Result tab, you can view the request URL and the response in JSON format.