すべてのプロダクト
Search
ドキュメントセンター

Function Compute:Go ランタイムのハンドラ

最終更新日:Mar 01, 2026

Go でハンドラ関数を定義し、実行可能なバイナリにコンパイルします。次に、Function Compute コンソール[ハンドラ] パラメーターをそのバイナリの名前に設定します。Function Compute は、関数が呼び出されるたびにこのハンドラを実行します。

説明

HTTP トリガーまたはカスタムドメイン名を使用して関数にアクセスする場合は、HTTP レスポンスを定義する前にリクエスト構造体を取得する必要があります。詳細については、「HTTP トリガーを使用した関数の呼び出し」をご参照ください。

クイックスタート

SDK パッケージ github.com/aliyun/fc-runtime-go-sdk/fc をインポートし、ハンドラ関数を実装して、main() 内で fc.Start に渡します。

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

このハンドラは、key フィールドを持つ JSON イベントを受け入れ、挨拶の文字列を返します。

{
  "key": "value"
}

コードの解説

要素目的
package mainGo の実行可能ファイルに必要なエントリパッケージ
github.com/aliyun/fc-runtime-go-sdk/fcFunction Compute Go SDK
context関数の呼び出しにランタイムコンテキストを提供
HandleRequest(ctx context.Context, event StructEvent) (string, error)ハンドラ関数:コンテキストと型付けされたイベントを受け取り、文字列とエラーを返す
fc.Start(HandleRequest)ハンドラを Function Compute に登録し、ランタイムループを開始する

コンテキストオブジェクトの詳細については、「コンテキスト」をご参照ください。エラー処理については、「エラー処理」をご参照ください。

ビルドとデプロイ

Go モジュールを初期化し、Function Compute SDK をインストールします。

go mod init my-fc-function
go get github.com/aliyun/fc-runtime-go-sdk

ハンドラを Linux バイナリにコンパイルします (Function Compute は Linux 上で実行されます)。

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o main main.go

Function Compute コンソールの [ハンドラ] パラメーターを main (コンパイルされたバイナリの名前) に設定します。関数の作成手順については、「イベント関数の作成」をご参照ください。

ハンドラのシグネチャ

ハンドラは以下のルールに従う必要があります。

  • 関数でなければなりません。

  • 0 から 2 個の入力パラメーターを受け入れます。2 つのパラメーターを使用する場合、最初のパラメーターは context.Context である必要があります。

  • 0 から 2 個の値を返します。単一の戻り値は error 型でなければなりません。2 つの戻り値の場合、2 番目の値は error でなければなりません。

すべての有効なシグネチャ:

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)

InputTypeOutputType は、標準ライブラリ encoding/json と互換性がある必要があります。Function Compute は json.Unmarshal で入力を逆シリアル化し、json.Marshal で出力をシリアル化します。詳細については、「JSON Unmarshal」をご参照ください。

入力イベントの型

イベントパラメーターは複数の Go の型をサポートしています。ユースケースに合った型を選択してください。

イベントの型ユースケース
構造体フィールドが既知の厳密に型付けされたイベントevent-struct.go
string生の文字列入力event-string.go
map[string]interface{}動的または緩やかに型付けされたイベントevent-map.go

その他の例については、「fc-runtime-go-sdk/examples」をご参照ください。

HTTP トリガーのハンドラ

HTTP トリガーまたはカスタムドメイン名経由で HTTP リクエストを処理するには、SDK の events パッケージにある HTTPTriggerEventHTTPTriggerResponse 構造体を使用します。

HTTP トリガーイベントの処理

package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/aliyun/fc-runtime-go-sdk/events"
	"github.com/aliyun/fc-runtime-go-sdk/fc"
)

type HTTPTriggerEvent events.HTTPTriggerEvent
type HTTPTriggerResponse events.HTTPTriggerResponse

func (h HTTPTriggerEvent) String() string {
	jsonBytes, err := json.MarshalIndent(h, "", "  ")
	if err != nil {
		return ""
	}
	return string(jsonBytes)
}

func NewHTTPTriggerResponse(statusCode int) *HTTPTriggerResponse {
	return &HTTPTriggerResponse{StatusCode: statusCode}
}

func (h *HTTPTriggerResponse) String() string {
	jsonBytes, err := json.MarshalIndent(h, "", "  ")
	if err != nil {
		return ""
	}
	return string(jsonBytes)
}

func (h *HTTPTriggerResponse) WithStatusCode(statusCode int) *HTTPTriggerResponse {
	h.StatusCode = statusCode
	return h
}

func (h *HTTPTriggerResponse) WithHeaders(headers map[string]string) *HTTPTriggerResponse {
	h.Headers = headers
	return h
}

func (h *HTTPTriggerResponse) WithIsBase64Encoded(isBase64Encoded bool) *HTTPTriggerResponse {
	h.IsBase64Encoded = isBase64Encoded
	return h
}

func (h *HTTPTriggerResponse) WithBody(body string) *HTTPTriggerResponse {
	h.Body = body
	return h
}

func HandleRequest(event HTTPTriggerEvent) (*HTTPTriggerResponse, error) {
	fmt.Printf("event: %v\n", event)
	if event.Body == nil {
		return NewHTTPTriggerResponse(http.StatusBadRequest).
			WithBody(fmt.Sprintf("the request did not come from an HTTP Trigger, event: %v", event)), nil
	}

	reqBody := *event.Body
	if event.IsBase64Encoded != nil && *event.IsBase64Encoded {
		decodedByte, err := base64.StdEncoding.DecodeString(*event.Body)
		if err != nil {
			return NewHTTPTriggerResponse(http.StatusBadRequest).
				WithBody(fmt.Sprintf("HTTP Trigger body is not base64 encoded, err: %v", err)), nil
		}
		reqBody = string(decodedByte)
	}
	return NewHTTPTriggerResponse(http.StatusOK).WithBody(reqBody), nil
}

func main() {
	fc.Start(HandleRequest)
}

このハンドラは、HTTPTriggerEvent から HTTP リクエストボディを読み取り、Base64 エンコードされている場合はデコードして、レスポンスで返します。リクエストとレスポンスの構造体は github.com/aliyun/fc-runtime-go-sdk/events から取得します。ペイロードのフォーマットの詳細については、「HTTP トリガーを使用した関数の呼び出し」をご参照ください。

関数の呼び出し

前提条件

開始する前に、以下を確認してください。

  • 前述のハンドラコードを使用して Go ランタイムで関数が作成されていること

  • 関数に HTTP トリガーが設定されていること

設定手順については、「イベント関数の作成」および「HTTP トリガーの設定」をご参照ください。

操作手順

  1. Function Compute コンソールにログインします。左側のナビゲーションウィンドウで、[関数] をクリックします。

  2. 上部のナビゲーションバーでリージョンを選択します。[関数] ページで、管理する関数をクリックします。

  3. [トリガー] タブをクリックします。HTTP トリガーのパブリックエンドポイントをコピーします。

  4. エンドポイントにリクエストを送信します。

       curl -i "https://http-trigger-demo.cn-shanghai.fcapp.run" -d "Hello FC!"
重要
  • HTTP トリガーの [認証方式][認証なし] に設定されている場合、curl または Postman を使用して直接関数を呼び出します。

  • [署名認証] または [JWT 認証] に設定されている場合は、必要な認証情報を含める必要があります。詳細については、「認証」をご参照ください。

[関数のテスト] のエラーに関するトラブルシューティング

このハンドラは、HTTP トリガーまたはカスタムドメイン名からの入力を想定しています。コンソールの [関数のテスト] ボタンで呼び出すと、HTTP トリガーのペイロードではなく、標準のイベントペイロードが送信されます。これにより、400 エラーが発生します。

{
    "statusCode": 400,
    "body": "the request did not come from an HTTP Trigger, event: {\n  \"version\": null,\n  \"rawPath\": null,\n  \"headers\": null,\n  \"queryParameters\": null,\n  \"body\": null,\n  \"isBase64Encoded\": null,\n  \"requestContext\": null\n}"
}

ソースに関係なく生のイベントペイロードを検査するには、[]byte ハンドラを使用します。

// GetRawRequestEvent は生のイベントをレスポンスボディとして返します
func GetRawRequestEvent(event []byte) (*HTTPTriggerResponse, error) {
	fmt.Printf("raw event: %s\n", string(event))
	return NewHTTPTriggerResponse(http.StatusOK).WithBody(string(event)), nil
}

func main() {
	fc.Start(GetRawRequestEvent)
}

参考資料