請求處理程序(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。