使用 Node.js (第 1 代) 建立及部署 HTTP Cloud Run 函式

本指南將逐步說明如何使用 Node.js 執行階段編寫 Cloud Run 函式。Cloud Run 函式分為兩種類型:

  • HTTP 函式,可從標準 HTTP 要求叫用。
  • 事件驅動函式,用於處理 Cloud 基礎架構中的事件,例如 Pub/Sub 主題上的訊息,或 Cloud Storage 值區中的變更。

這個範例說明如何建立簡單的 HTTP 函式。

事前準備

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  8. 安裝並初始化 gcloud CLI
  9. 更新並安裝 gcloud 元件:
    gcloud components update
  10. 準備開發環境。

    前往 Node.js 設定指南

  11. 建立函式

    1. 在本機系統上為函式程式碼建立目錄:

      Linux 或 Mac OS X

      mkdir ~/helloworld
      cd ~/helloworld
      

      Windows

      mkdir %HOMEPATH%\helloworld
      cd %HOMEPATH%\helloworld
      
    2. helloworld 目錄中建立 index.js 檔案,並加入以下內容:

      const functions = require('@google-cloud/functions-framework');
      const escapeHtml = require('escape-html');
      
      /**
       * Responds to an HTTP request using data from the request body parsed according
       * to the "content-type" header.
       *
       * @param {Object} req Cloud Function request context.
       * @param {Object} res Cloud Function response context.
       */
      functions.http('helloHttp', (req, res) => {
        res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`);
      });

      此範例函式採用在 HTTP 要求中提供的名稱,並傳回問候語,如未提供任何名稱,系統會傳回「Hello World!」。

    指定依附元件

    Node.js 中的依附元件會儲存在名為 package.json 的檔案中。您可以手動建立這個檔案,也可以使用 npm 指令建立。

    • 如要使用 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 檔案,並加入下列內容:

      {
        "name": "nodejs-docs-samples-functions-hello-world-http",
        "version": "0.0.1",
        "private": true,
        "license": "Apache-2.0",
        "author": "Google Inc.",
        "repository": {
          "type": "git",
          "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
        },
        "engines": {
          "node": ">=16.0.0"
        },
        "scripts": {
          "unit-test": "c8 mocha -p -j 2 test/index.test.js test/*unit*test.js test/*integration*test.js --timeout=6000 --exit",
          "system-test": "c8 mocha -p -j 2 test/*system*test.js --timeout=600000 --exit",
          "all-test": "npm run unit-test && npm run system-test",
          "test": "npm -- run unit-test"
        },
        "dependencies": {
          "@google-cloud/functions-framework": "^3.1.0",
          "escape-html": "^1.0.3"
        },
        "devDependencies": {
          "c8": "^10.0.0",
          "gaxios": "^6.0.0",
          "mocha": "^10.0.0",
          "sinon": "^18.0.0",
          "supertest": "^7.0.0",
          "wait-port": "^1.0.4"
        }
      }
      

    部署函式

    如要使用 HTTP 觸發條件部署函式,請在 helloworld 目錄中執行下列指令:

    gcloud functions deploy helloHttp --no-gen2 --runtime nodejs20 --trigger-http --allow-unauthenticated
    

    --allow-unauthenticated 旗標可讓您不必驗證就能使用函式。如要要求驗證,請略過該旗標。

    測試函式

    1. 函式完成部署後,請記下 httpsTrigger.url 屬性,或使用下列指令找到這個屬性:

      gcloud functions describe helloHttp
      

      內容應該會類似這樣:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp
    2. 透過您的瀏覽器造訪這個網址。您應該會看到「Hello World!」訊息。

      請嘗試透過 HTTP 要求傳送名稱,例如使用下列網址:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp?name=NAME

      您應該會看到「Hello NAME!」訊息

    查看記錄

    您可以使用 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 的記錄。