本文介绍Go事件请求处理程序的结构和特点。
使用示例
在Go语言的代码中,您需要引入官方的SDK库github.com/aliyun/fc-runtime-go-sdk/fc,并实现handler函数和main函数。示例如下:
package main
import (
"fmt"
"context"
"github.com/aliyun/fc-runtime-go-sdk/fc"
)
type StructEvent struct {
Key string `json:"key"`
}
func HandleRequest(ctx context.Context, event StructEvent) (string, error) {
return fmt.Sprintf("hello, %s!", event.Key), nil
}
func main() {
fc.Start(HandleRequest)
}传入的event参数是一个包含key属性的JSON字符串,示例如下。
{
"key": "value"
}具体的示例解析如下:
package main:在Go语言中,Go应用程序都包含一个名为main的包。import:需要引用函数计算依赖的包,主要包括以下包:github.com/aliyun/fc-runtime-go-sdk/fc:函数计算Go语言的核心库。context:函数计算Go语言的Context对象。
func HandleRequest(ctx context.Context, event StructEvent) (string, error):处理事件请求的方法(即Handler),需包含将要执行的代码,参数含义如下:func main():运行FC函数代码的入口点,Go程序必须包含main函数。通过添加代码fc.Start(HandleRequest),您的程序即可运行在阿里云函数计算平台。重要HTTP请求处理程序和事件请求处理程序的启动方法不同。如果是事件请求处理程序,您需要在
main函数中调用fc.Start函数。如果是HTTP请求处理程序,您需要在main函数中调用fc.StartHttp函数。
Event Handler签名
下面列举出了有效的Event Handler签名,其中InputType和OutputType与encoding/json标准库兼容。
函数计算会使用json.Unmarshal方法对传入的InputType进行反序列化,以及使用json.Marshal方法对返回的OutputType进行序列化。关于如何反序列化函数的返回数据,请参考JSON Unmarshal。
func ()func () errorfunc (InputType) errorfunc () (OutputType, error)func (InputType) (OutputType, error)func (context.Context) errorfunc (context.Context, InputType) errorfunc (context.Context) (OutputType, error)func (context.Context, InputType) (OutputType, error)
Event Handler的使用需遵循以下规则:
Handler必须是一个函数。
Handler支持0~2个输入参数。如果有2个参数,则第一个参数必须是
context.Context。Handler支持0~2个返回值。如果有1个返回值,则必须是
error类型;如果有2个返回值,则第2个返回值必须是error。
事件函数的Handler示例代码:
event-struct.go:
event为Struct类型的示例代码。event-string.go:
event为String类型的示例代码。event-map.go:
event为map[string]interface{}类型的示例代码。
更多Handler示例,请参见examples。
Context
Context的详细使用方法,请参见上下文。