首页 函数计算(旧版) 操作指南 代码开发 Go 事件请求处理程序(Event Handler)

事件请求处理程序(Event Handler)

更新时间: 2023-09-06 16:32:09

本文介绍Go事件请求处理程序的结构和特点。

使用示例

在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("hello,%s !", event.Key), nil:简单地返回hello信息,其中包含传入的eventnil表示没有报错。

  • func main():运行FC函数代码的入口点,Go程序必须包含main函数。通过添加代码fc.Start(HandleRequest),您的程序即可运行在阿里云函数计算平台。

    重要

    HTTP请求处理程序和事件请求处理程序的启动方法不同。如果是事件请求处理程序,您需要在main函数中调用fc.Start函数。如果是HTTP请求处理程序,您需要在main函数中调用fc.StartHttp函数。

Event Handler签名

下面列举出了有效的Event Handler签名,其中InputTypeOutputTypeencoding/json标准库兼容。

函数计算会使用json.Unmarshal方法对传入的InputType进行反序列化,以及使用json.Marshal方法对返回的OutputType进行序列化。关于如何反序列化函数的返回数据,请参考JSON Unmarshal

  • 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)

Event Handler的使用需遵循以下规则:

  • Handler必须是一个函数。

  • Handler支持0~2个输入参数。如果有2个参数,则第一个参数必须是context.Context

  • Handler支持0~2个返回值。如果有1个返回值,则必须是error类型;如果有2个返回值,则第2个返回值必须是error

事件函数的Handler示例代码:

更多Handler示例,请参见examples

Context

Context的详细使用方法,请参见上下文

阿里云首页 函数计算(旧版) 相关技术圈