Go で Cloud Run functions の HTTP 関数を作成してデプロイする(第 1 世代)
このガイドでは、Go ランタイムを使用して Cloud Run functions の関数を記述するプロセスを説明します。Cloud Run functions には次の 2 つのタイプがあります。
- HTTP 関数。標準的な HTTP リクエストから呼び出します。
- イベント ドリブン関数。Pub/Sub トピックのメッセージや Cloud Storage バケットの変更など、Cloud インフラストラクチャのイベントを処理するために使用します。
次のサンプルでは、簡単な HTTP 関数を作成しています。
始める前に
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions and Cloud Build APIs.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions and Cloud Build APIs.
- gcloud CLI をインストールして初期化します。
gcloud
コンポーネントを更新してインストールします。gcloud components update
- 開発環境を準備します。
関数コードで使用するため、ローカル システムにディレクトリを作成します。
Linux / Mac OS X
mkdir ~/helloworld cd ~/helloworld
Windows
mkdir %HOMEPATH%\helloworld cd %HOMEPATH%\helloworld
helloworld
ディレクトリに、次の内容のファイルをhello_http.go
という名前で作成します。このサンプル関数は、HTTP リクエストで指定された名前を使用して挨拶を返します。名前が指定されていない場合は、「Hello World!」と返します。
関数がデプロイされたら、
httpsTrigger.url
プロパティをメモするか、次のコマンドを使用して検索します。gcloud functions describe HelloHTTP
次のようになります。
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP
ブラウザでこの URL にアクセスするか、次のコマンドを実行して cURL を使用します。
curl https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP
「Hello, World!」というメッセージが表示されます。次のコマンドを実行して、HTTP リクエストで名前を渡します。
curl -X POST https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP -H "Content-Type:application/json" -d '{"name":"NAME"}'
「Hello,
NAME
!」というメッセージが表示されます。
関数を作成する
依存関係を指定する
このサンプル関数は Go 標準ライブラリ パッケージのみを使用します。パッケージをインポートするだけで完了し、依存関係を宣言する必要はありません。
関数で標準ライブラリ以外の依存関係を必要とする場合は、go.mod
ファイルまたは vendor
ディレクトリを使用して依存関係を指定する必要があります。詳細については、Go での依存関係の指定をご覧ください。
関数をデプロイする
HTTP トリガーを使用して関数をデプロイするには、helloworld
ディレクトリで次のコマンドを実行します。ご使用のバージョンに応じて、--runtime
フラグの値として go113
または go111
を指定します。
gcloud functions deploy HelloHTTP --no-gen2 --runtime go121 --trigger-http --allow-unauthenticated
--allow-unauthenticated
フラグを使用すると、認証なしで関数にアクセスできます。認証を要求するには、フラグを省略します。
関数をテストする
ログを表示する
Cloud Run functions のログは、Google Cloud CLI を使用して、また Cloud Logging UI で表示できます。
コマンドライン ツールを使用する
gcloud CLI を使用して関数のログを表示するには、logs read
コマンドの後に関数の名前を続けます。
gcloud functions logs read HelloHTTP
出力は次のようになります。
LEVEL NAME EXECUTION_ID TIME_UTC LOG D HelloHTTP buv9ej2k1a7r 2019-09-20 13:23:18.910 Function execution started D HelloHTTP buv9ej2k1a7r 2019-09-20 13:23:18.913 Function execution took 4 ms, finished with status code: 200
Logging ダッシュボードを使用する
Google Cloud コンソールから Cloud Run functions のログを表示することもできます。