使用樣本
在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字串,樣本如下。
具體的樣本解析如下:
package main
:在Go語言中,Go應用程式都包含一個名為main
的包。
import
:需要引用Function Compute依賴的包,主要包括以下包:
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
資訊,其中包含傳入的event
。nil
表示沒有報錯。
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 () 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)
更多Handler樣本,請參見examples。
Context
Context的詳細使用方法,請參見上下文。