使用 Node.js (第 1 代) 建立及部署 HTTP Cloud Run 函式
本指南將逐步說明如何使用 Node.js 執行階段編寫 Cloud Run 函式。Cloud Run 函式分為兩種類型:
- HTTP 函式,可從標準 HTTP 要求叫用。
- 事件驅動函式,用於處理 Cloud 基礎架構中的事件,例如 Pub/Sub 主題上的訊息,或 Cloud Storage 值區中的變更。
這個範例說明如何建立簡單的 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.
-
Make sure 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.
-
Make sure 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
目錄中建立index.js
檔案,並加入以下內容:此範例函式採用在 HTTP 要求中提供的名稱,並傳回問候語,如未提供任何名稱,系統會傳回「Hello World!」。
如要使用
npm
建立package.json
依附元件檔案,請執行下列指令:npm init npm install c8 gaxios mocha sinon supertest wait-port --save-dev npm install @google-cloud/functions-framework escape-html
如要手動建構
package.json
檔案,請在helloworld
目錄中建立package.json
檔案,並加入下列內容:函式完成部署後,請記下
httpsTrigger.url
屬性,或使用下列指令找到這個屬性:gcloud functions describe helloHttp
內容應該會類似這樣:
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp
透過您的瀏覽器造訪這個網址。您應該會看到「Hello World!」訊息。
請嘗試透過 HTTP 要求傳送名稱,例如使用下列網址:
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp?name=NAME
您應該會看到「Hello
NAME
!」訊息
建立函式
指定依附元件
Node.js 中的依附元件會儲存在名為 package.json
的檔案中。您可以手動建立這個檔案,也可以使用 npm 指令建立。
部署函式
如要使用 HTTP 觸發條件部署函式,請在 helloworld
目錄中執行下列指令:
gcloud functions deploy helloHttp --no-gen2 --runtime nodejs20 --trigger-http --allow-unauthenticated
--allow-unauthenticated
旗標可讓您不必驗證就能使用函式。如要要求驗證,請略過該旗標。
測試函式
查看記錄
您可以使用 Google Cloud CLI,以及在 Cloud Logging UI 中查看 Cloud Run functions 的記錄。
使用指令列工具
如要透過 gcloud CLI 查看函式的記錄檔,請使用 logs read
指令加上函式的名稱:
gcloud functions logs read helloHttp
輸出應會如下所示:
LEVEL NAME EXECUTION_ID TIME_UTC LOG D helloHttp rvb9j0axfclb 2019-09-18 22:06:25.983 Function execution started D helloHttp rvb9j0axfclb 2019-09-18 22:06:26.001 Function execution took 19 ms, finished with status code: 200
使用記錄資訊主頁
您也可以從Google Cloud 控制台查看 Cloud Run functions 的記錄。