HTTP 教學課程


這個簡易教學課程示範如何編寫、部署及觸發 HTTP Cloud Run 函式

目標

費用

在本文件中,您會使用 Google Cloud的下列計費元件:

  • Cloud Run functions

如要根據預測用量估算費用,請使用 Pricing Calculator

初次使用 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 Functions and Cloud Build APIs.

    Enable the APIs

  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 Functions and Cloud Build APIs.

    Enable the APIs

  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. 如果您已安裝 gcloud CLI,請執行下列指令來更新:

    gcloud components update
  15. 準備開發環境。 <0x

準備應用程式

  1. 將應用程式存放區範例複製到本機電腦中:

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    您也可以 下載 zip 格式的範例,然後解壓縮該檔案。

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    您也可以 下載 zip 格式的範例,然後解壓縮該檔案。

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    您也可以 下載 zip 格式的範例,然後解壓縮該檔案。

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    您也可以 下載 zip 格式的範例,然後解壓縮該檔案。

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    您也可以 下載 zip 格式的範例,然後解壓縮該檔案。

  2. 變更為包含 Cloud Run 函式程式碼範例的目錄:

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/helloworld/

    Java

    cd java-docs-samples/functions/helloworld/helloworld/

    Ruby

    cd ruby-docs-samples/functions/helloworld/

  3. 查看程式碼範例:

    Node.js

    const functions = require('@google-cloud/functions-framework');
    
    // Register an HTTP function with the Functions Framework that will be executed
    // when you make an HTTP request to the deployed function's endpoint.
    functions.http('helloGET', (req, res) => {
      res.send('Hello World!');
    });

    Python

    import functions_framework
    
    @functions_framework.http
    def hello_get(request):
        """HTTP Cloud Function.
        Args:
            request (flask.Request): The request object.
            <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
        Returns:
            The response text, or any set of values that can be turned into a
            Response object using `make_response`
            <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
        Note:
            For more information on how Flask integrates with Cloud
            Functions, see the `Writing HTTP functions` page.
            <https://cloud.google.com/functions/docs/writing/http#http_frameworks>
        """
        return "Hello World!"
    
    

    Go

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"fmt"
    	"net/http"
    )
    
    // HelloGet is an HTTP Cloud Function.
    func HelloGet(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprint(w, "Hello, World!")
    }
    

    Java

    
    package functions;
    
    import com.google.cloud.functions.HttpFunction;
    import com.google.cloud.functions.HttpRequest;
    import com.google.cloud.functions.HttpResponse;
    import java.io.BufferedWriter;
    import java.io.IOException;
    
    public class HelloWorld implements HttpFunction {
      // Simple function to return "Hello World"
      @Override
      public void service(HttpRequest request, HttpResponse response)
          throws IOException {
        BufferedWriter writer = response.getWriter();
        writer.write("Hello World!");
      }
    }

    Ruby

    require "functions_framework"
    
    FunctionsFramework.http "hello_get" do |_request|
      # The request parameter is a Rack::Request object.
      # See https://www.rubydoc.info/gems/rack/Rack/Request
    
      # Return the response body as a string.
      # You can also return a Rack::Response object, a Rack response array, or
      # a hash which will be JSON-encoded into a response.
      "Hello World!"
    end

部署函式

如要使用 HTTP 觸發條件部署函式,請在包含範例程式碼的目錄中執行下列指令 (如果是 Java,則在 pom.xml 檔案中執行):

Node.js

gcloud functions deploy helloGET \
--runtime nodejs20 --trigger-http

使用 --runtime 標記指定支援的 Node.js 版本執行階段 ID,以執行函式。

Python

gcloud functions deploy hello_get \
--runtime python312 --trigger-http

使用 --runtime 標記指定支援的 Python 版本執行階段 ID,以執行函式。

Go

gcloud functions deploy HelloGet \
--runtime go121 --trigger-http

使用 --runtime 標記指定支援的 Go 版本執行階段 ID,以執行函式。

Java

gcloud functions deploy java-http-function \
--entry-point functions.HelloWorld \
--runtime java17 \
--memory 512MB --trigger-http

使用 --runtime 標記指定支援的 Java 版本執行函式的執行階段 ID。

Ruby

gcloud functions deploy hello_get --runtime ruby33 --trigger-http

使用 --runtime 標記指定支援的 Ruby 版本執行階段 ID,以執行函式。

您可以選擇使用 --allow-unauthenticated 旗標,不必驗證就能使用函式。這項設定適用於測試,但除非您要建立公開 API 或網站,否則不建議在正式環境中使用。此外,根據公司政策設定,這項功能可能不適用於你。如要瞭解如何叫用需要驗證的函式,請參閱「叫用時進行驗證」。

觸發函式

如要對您的函式提出 HTTP 要求,請執行下列指令:

Node.js

curl "https://REGION-PROJECT_ID.cloudfunctions.net/helloGET" 

Python

curl "https://REGION-PROJECT_ID.cloudfunctions.net/hello_get" 

Go

curl "https://REGION-PROJECT_ID.cloudfunctions.net/HelloGet" 

Java

curl "https://REGION-PROJECT_ID.cloudfunctions.net/java-http-function" 

Ruby

curl "https://REGION-PROJECT_ID.cloudfunctions.net/hello_get" 

其中

  • REGION 是函式部署的地區。函式完成部署時,終端機中會顯示這個值。
  • PROJECT_ID 是您的 Cloud 專案 ID。當您的函式部署完成時,可以在您的終端機中看見它。

您也可以在瀏覽器中前往已部署函式的端點,查看「Hello World!」訊息。

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

刪除專案

如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。

如要刪除專案:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

刪除函式

刪除 Cloud Run 函式不會移除儲存在 Cloud Storage 中的任何資源。

如要刪除本教學課程中建立的 Cloud Run 函式,請執行下列指令:

Node.js

gcloud functions delete helloGET 

Python

gcloud functions delete hello_get 

Go

gcloud functions delete HelloGet 

Java

gcloud functions delete java-http-function 

Ruby

gcloud functions delete hello_get 

您也可以從 Google Cloud 控制台刪除 Cloud Run 函式。