本文介紹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:需要引用Function Compute依賴的包,主要包括以下包:github.com/aliyun/fc-runtime-go-sdk/fc:Function ComputeGo語言的核心庫。context:Function ComputeGo語言的Context對象。
func HandleRequest(ctx context.Context, event StructEvent) (string, error):處理事件請求的方法(即Handler),需包含將要執行的代碼,參數含義如下:func main():運行FC函數代碼的進入點,Go程式必須包含main函數。通過添加代碼fc.Start(HandleRequest),您的程式即可運行在阿里雲Function Compute平台。重要HTTP請求處理常式和事件請求處理常式的啟動方法不同。如果是事件請求處理常式,您需要在
main函數中調用fc.Start函數。如果是HTTP請求處理常式,您需要在main函數中調用fc.StartHttp函數。
Event Handler簽名
下面列舉出了有效Event Handler簽名,其中InputType和OutputType與encoding/json標準庫相容。
Function Compute會使用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的詳細使用方法,請參見上下文。