请求处理程序(Handler)
更新时间 2024-12-10 12:14:36
最近更新时间: 2024-12-10 12:14:36
本文介绍如何使用Go请求处理程序响应接收到的事件并执行相应的业务逻辑。
请求处理程序
请求处理程序是您提供的一个方法。当您的函数被调用时,函数计算会运行该方法处理请求。
您可以通过函数计算控制台页面配置请求处理程序,对于Go语言的函数,请求处理程序会被被编译为一个可执行的二进制文件。例如,您的可执行二进制文件名为handler,则请求处理程序直接配置为handler。
在Go语言的代码中,您需要引入官方的SDK库 gitee.com/ctyunfaas/cf-runtime-go-sdk/cf,并实现 handler方法和 main方法。示例如下:
package main
import (
"log"
"gitee.com/ctyunfaas/cf-runtime-go-sdk/cf"
)
func main() {
cf.Start(HandleRequest)
}
func HandleRequest() (string, error) {
log.Println("hello world!")
return "hello world"!", nil
}
Handler方法签名
下面列举出了有效的Event Handler方法签名,其中 InputType和 OutputType与 encoding/json标准库兼容。
函数计算会使用 json.Unmarshal方法对传入的 InputType进行反序列化,以及使用 json.Marshal方法对返回的 OutputType进行序列化。
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)
Handler的使用需遵循以下规则:
- Handler必须是一个方法。
- Handler支持0~2个输入参数。如果有2个参数,则第一个参数必须是
context.Context。 - Handler支持0~2个返回值。如果有1个返回值,则必须是
error类型;如果有2个返回值,则第2个返回值必须是error。