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

本指南將逐步說明如何使用 Go 執行階段,撰寫 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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

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

    前往 Go 設定指南

  11. 建立函式

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

      Linux 或 Mac OS X

      mkdir ~/helloworld
      cd ~/helloworld
      

      Windows

      mkdir %HOMEPATH%\helloworld
      cd %HOMEPATH%\helloworld
      
    2. helloworld 目錄中建立名為 hello_http.go 的檔案,並加入以下內容:

      
      // Package helloworld provides a set of Cloud Functions samples.
      package helloworld
      
      import (
      	"encoding/json"
      	"fmt"
      	"html"
      	"net/http"
      
      	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
      )
      
      func init() {
      	functions.HTTP("HelloHTTP", HelloHTTP)
      }
      
      // HelloHTTP is an HTTP Cloud Function with a request parameter.
      func HelloHTTP(w http.ResponseWriter, r *http.Request) {
      	var d struct {
      		Name string `json:"name"`
      	}
      	if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
      		fmt.Fprint(w, "Hello, World!")
      		return
      	}
      	if d.Name == "" {
      		fmt.Fprint(w, "Hello, World!")
      		return
      	}
      	fmt.Fprintf(w, "Hello, %s!", html.EscapeString(d.Name))
      }
      

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

    指定依附元件

    這個範例函式只使用 Go 標準程式庫套件,因此除了匯入套件之外,您不需要宣告任何依附元件。

    如果函式需要標準程式庫以外的依附元件,您必須透過 go.mod 檔案或 vendor 目錄提供依附元件。詳情請參閱「在 Go 中指定依附元件」。

    部署函式

    如要使用 HTTP 觸發條件部署函式,請在 helloworld 目錄中執行下列指令,並根據您使用的版本,將 go113go111 指定為 --runtime 旗標的值:

    gcloud functions deploy HelloHTTP --no-gen2 --runtime go121 --trigger-http --allow-unauthenticated

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

    測試函式

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

      gcloud functions describe HelloHTTP
      

      內容應該會類似這樣:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP
    2. 在瀏覽器中前往這個網址,或執行下列指令來使用 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!」訊息

    查看記錄

    您可以使用 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  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

    使用記錄資訊主頁

    您也可以從Google Cloud 控制台查看 Cloud Run functions 的記錄。