Go语言事件请求处理程序(EventHandler)
在Go语言的代码中,您需要引入官方的SDK库 aliyun/serverless/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),需包含将要执行的代码,参数含义如下:ctx context.Context:为您的FC函数调用提供在调用时的运行上下文信息。更多信息,请参见下文。event StructEvent:调用函数时传入的数据,可以支持多种类型。string, error:返回两个值,字符串和错误信息。更多信息,请参见错误处理。return fmt.Sprintf("Hi,%s !", event.Key), nil:简单地返回hello信息,其中包含传入的event。nil表示没有报错。 func main():运行FC函数代码的入口点,Go程序必须包含main函数。通过添加代码fc.Start(HandleRequest),您的程序即可运行在阿里云函数计算平台。 注意 HTTP请求处理程序和事件请求处理程序的启动方法不同。如果是事件请求处理程序,您需要在main函数中调用fc.Start函数。如果是HTTP请求处理程序,您需要在main函数中调用
fc.StartHttp函数。Event Handler签名
有效的Event Handler签名如下: func () func () error func (InputType) error func () (OutputType, error) func (InputType) (OutputType, error) func (context.Context) error func (context.Context, InputType) error func (context.Context) (OutputType, error) func (context.Context, InputType) (OutputType, error)
其中,InputType和OutputType与encoding/json标准库兼容。
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{}类型的示例代码。