本文介绍使用 Go SDK 的详细流程,包括环境要求、安装和快速使用三部分。

环境要求

您的系统需要达到环境要求,例如安装了 1.10.x 或以上版本的 Go 环境。

安装

使用 go get 下载安装 Go SDK 。

$ go get -u github.com/aliyun/alibaba-cloud-sdk-go/sdk          

如果您使用了 glide 管理依赖,您也可以使用 glide 来安装 Alibaba Cloud SDK for Go。

$ glide get github.com/aliyun/alibaba-cloud-sdk-go

另外,Alibaba Cloud SDK for Go 也会发布在 https://develop.aliyun.com/tools/sdk#/go

快速使用

在您开始之前,您需要注册阿里云账号并获取您的凭证。下文将以创建一个流程,发起一次执行并获取执行详情为例展示如何使用 Go SDK 调用 Serverless 工作流服务。

请求方式

package main

import (
    "fmt"
    "time"

    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
    "github.com/aliyun/alibaba-cloud-sdk-go/services/fnf"
)

var (
    flowDefinitionType = "FDL"
    flowName           = "xxx"
    flowDefinition     = `xxx`
    flowDescription    = "some descriptions"
    roleArn            = "acs:ram::${Your_Account_ID}:${Your_Role}"
    executionName      = "xxx"
)

// CreateFlow ...
func CreateFlow(cli *fnf.Client) (*fnf.CreateFlowResponse, error) {
    request := fnf.CreateCreateFlowRequest()
    request.Name = flowName
    request.Definition = flowDefinition
    request.Description = flowDescription
    request.Type = flowDefinitionType
    request.RoleArn = roleArn
    return cli.CreateFlow(request)
}

// StartExecution ...
func StartExecution(cli *fnf.Client) (*fnf.StartExecutionResponse, error) {
    request := fnf.CreateStartExecutionRequest()
    request.FlowName = flowName
    request.ExecutionName = executionName
    return cli.StartExecution(request)
}

// DescribeExecution ...
func DescribeExecution(cli *fnf.Client) (*fnf.DescribeExecutionResponse, error) {
    request := fnf.CreateDescribeExecutionRequest()
    request.FlowName = flowName
    request.ExecutionName = executionName
    return cli.DescribeExecution(request)
}

// GetExecutionHistory ...
func GetExecutionHistory(cli *fnf.Client) (*fnf.GetExecutionHistoryResponse, error) {
    request := fnf.CreateGetExecutionHistoryRequest()
    // request.Limit and request.NextToken can set here. For easy demo, we passed.
    request.FlowName = flowName
    request.ExecutionName = executionName
    return cli.GetExecutionHistory(request)
}

创建客户端并利用上述函数发起一系列调用

说明 如果您需要不加改造进行调试的话,请将下述函数与上述请求方式代码块置于同一个文件中,避免在 import 时报错。
func main() {
    fnfCli, err := fnf.NewClientWithAccessKey("cn-hangzhou", "AccessID", "AccessKey")
    if err != nil {
        panic(err)
    }
    // Create a flow
    _, err = CreateFlow(fnfCli)
    if err != nil {
        panic(err)
    }
    // StartExecution
    _, err = StartExecution(fnfCli)
    if err != nil {
        panic(err)
    }
    time.Sleep(time.Second)
    // DescribeExecution
    desResp, err := DescribeExecution(fnfCli)
    if err != nil {
        panic(err)
    }
    fmt.Println(fmt.Sprintf("%s status: %s", desResp.Name, desResp.Status))
    // GetExecutionHistory
    _, err = GetExecutionHistory(fnfCli)
    if err != nil {
        panic(err)
    }
}