在 App Engine 上建構 Go 應用程式

區域 ID

REGION_ID 是 Google 根據您在建立應用程式時選取的地區所指派的縮寫代碼。此代碼不對應至國家/地區或省份,即使部分區域 ID 可能與常用的國家/地區和省份代碼相似。如果是 2020 年 2 月後建立的應用程式,App Engine 網址會包含 REGION_ID.r。如果是這段時間前建立的現有應用程式,網址可選擇是否包含地區 ID。

進一步瞭解區域 ID

這篇指南可協助您開始使用 App Engine,並熟悉開發、部署及管理 Go 應用程式的相關事務。

建構好應用程式後,您可以參閱其他教學課程,瞭解如何與其他 Google Cloud 服務整合,以及為應用程式新增更多功能。

費用

操作本指南步驟並不會產生任何費用,而單獨執行這個範例應用程式也不會超過您的免費配額

設定開發環境

您可以在本機電腦上使用自己熟悉的工具,也可以選擇使用 Cloud Shell。Cloud Shell 已預先安裝 Google Cloud CLI,並設定好環境,還提供許多其他功能

本機電腦

按照「設定開發環境」一文所述,安裝 Go 並設定 gcloud CLI。

Cloud Shell

啟動 Cloud Shell,Cloud Shell 包含所有您需要預先安裝的工具:

開啟 Cloud Shell

建立 Google Cloud 專案

專案為使用 Google Cloud的基礎要素,必須先有專案才能使用所有Google Cloud 服務。

  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 Build API.

    Enable the API

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  10. Enable the Cloud Build API.

    Enable the API

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

    gcloud init
  14. 建立您的 App Engine 應用程式及相關資源。您必須選擇建立的位置,而且一經設定即無法變更。
    gcloud app create
  15. 由於新專案中 Cloud Build 使用服務帳戶的預設行為有所變更,以及預設安全機構政策變更,您可能需要將額外角色授予部署服務帳戶。如要進一步瞭解如何授予特定角色,請參閱疑難排解指南
  16. 為 App Engine 撰寫基本網路服務

    瞭解如何撰寫網路服務及宣告執行階段設定。

    建立檔案結構

    您的服務會有以下的檔案結構:

    • go-app/:Go 服務的目錄。
      • app.yaml:服務的配置設定。
      • main.go:應用程式程式碼。

    建立 app.yaml 檔案

    每個 App Engine 專案都有 app.yaml 設定檔,可指定服務的執行階段環境設定。缺少這個檔案將無法部署服務。

    1. 為 Go 服務建立名為 go-app 的新資料夾:

      mkdir go-app

    2. go-app/ 資料夾中建立名為 app.yaml 的檔案,並新增下列內容:

      runtime: go123  # or another supported version
      

      這是 App Engine 應用程式的最簡單設定,會向 App Engine 表示您使用的是 Go。app.yaml 檔案可以指定其他 Go 版本、網路設定、資源調度設定等等。詳情請參閱app.yaml 參考資料

    建立 main.go 檔案

    本範例使用 net/http 套件來建立會顯示「Hello, World!」的 HTTP 伺服器。

    如要設定 main.go 檔案,請按照下列步驟操作:

    1. go-app/ 資料夾中,建立 main.go 檔案。

    2. 新增 package main 陳述式,將程式碼視為可執行的程式:

      package main
      

      如要成功部署服務,您必須在至少一個 Go 來源檔案的開頭定義 package main 陳述式。

    3. 匯入下列套件:

      import (
      	"fmt"
      	"log"
      	"net/http"
      	"os"
      )
      
    4. 定義您的 HTTP 處理常式:

      
      // indexHandler responds to requests with our greeting.
      func indexHandler(w http.ResponseWriter, r *http.Request) {
      	if r.URL.Path != "/" {
      		http.NotFound(w, r)
      		return
      	}
      	fmt.Fprint(w, "Hello, World!")
      }
      

      http.ResponseWriter 物件會組合 HTTP 伺服器回應,因此將資料寫入該物件,即可將資料傳送至瀏覽器。http.Request 物件是代表傳入 HTTP 要求的資料結構。

    5. 登錄 HTTP 處理常式:

      
      func main() {
      	http.HandleFunc("/", indexHandler)
      
      	port := os.Getenv("PORT")
      	if port == "" {
      		port = "8080"
      		log.Printf("Defaulting to port %s", port)
      	}
      
      	log.Printf("Listening on port %s", port)
      	if err := http.ListenAndServe(":"+port, nil); err != nil {
      		log.Fatal(err)
      	}
      }
      

      main 函式是可執行程式的進入點,因此會啟動應用程式。該函式一開始會呼叫 http.HandleFunc 函式,後者會通知 http 套件使用 indexHandler 函式處理所有傳送至網路根目錄 ("/") 的要求。

      如果尚未設定 PORT 環境變數,8080 通訊埠會做為預設值來使用。應用程式在 App Engine 上執行時,系統會為您設定 PORT 環境變數,但您在本機測試應用程式時,可以將 PORT 設為任何偏好的值。

    在 App Engine 上部署網路服務

    1. app.yaml 檔案所在的 go-app 目錄中,使用下列指令將網路服務部署至 App Engine:

      gcloud app deploy

    2. 如要啟動瀏覽器並在 https://PROJECT_ID.REGION_ID.r.appspot.com 查看網路服務,請執行下列指令:

      gcloud app browse

    恭喜!您剛剛已在 App Engine 上建立服務並部署完成。

    服務和版本

    您為應用程式部署的第一個服務會是預設服務。您可以在 app.yaml 檔案中指定服務名稱,但如果省略名稱,系統會將其視為 default。您可以部署預設服務以外的多項服務

    您隨時都能執行 gcloud app deploy 指令來更新服務。每當您進行部署作業時,系統會建立新版本並自動將流量轉送至最新版本。

    如要確認建立服務及部署版本:

    1. 在 Google Cloud 控制台中查看 App Engine 服務:

      查看服務

      畫面上應該會列出一個名為 default 的服務。default 服務可透過下列網址公開存取:

      https://PROJECT_ID.REGION_ID.r.appspot.com

    2. 查看您的版本:

      查看版本

      畫面上應該會列出一個加上時間戳記的版本,且與您的部署互相對應。

    如需瞭解將要求傳送至特定服務和版本的方式,請參閱要求的轉送方式

    後續步驟

    恭喜!您剛剛已完成設定網路應用程式並將其部署至 App Engine。

    請瀏覽下列頁面,瞭解如何將其他功能新增至您的應用程式: