Your First Function: Go

This guide takes you through the process of writing a Cloud Function using the Go runtime. There are two types of Cloud Functions:

  • An HTTP function, which you invoke from standard HTTP requests.
  • A background function, which you use to handle events from your Cloud infrastructure, such as messages on a Cloud Pub/Sub topic, or changes in a Cloud Storage bucket.

The sample shows how to create a simple HTTP function.

Guide structure

  1. Creating a GCP project using Cloud SDK
  2. Creating a function
  3. Specifying dependencies
  4. Deploying your function
  5. Testing your function

Creating a GCP project using Cloud SDK

  1. 登入您的 Google 帳戶。

    如果您沒有帳戶,請申請新帳戶

  2. 在 GCP Console 的專案選擇器頁面中,選取或建立 GCP 專案。

    前往專案選取器頁面

  3. 請確認您已啟用 Google Cloud Platform 專案的計費功能。瞭解如何確認您已啟用專案的計費功能

  4. 啟用Cloud Functions必要的 。

    啟用 API

  5. Install and initialize the Cloud SDK.
  6. Update and install gcloud components:
    gcloud components update
  7. Need a command prompt? You can use the Google Cloud Shell. The Google Cloud Shell is a command line environment that already includes the Google Cloud SDK, so you don't need to install it. The Google Cloud SDK also comes preinstalled on Google Compute Engine Virtual Machines.

  8. Prepare your development environment.

    Go to the Go setup guide

Creating a function

  1. Create a directory on your local system for the function code:

    Linux or Mac OS X

    mkdir ~/gcf_hello_world
    cd ~/gcf_hello_world
    

    Windows

    mkdir %HOMEPATH%\gcf_hello_world
    cd %HOMEPATH%\gcf_hello_world
    
  2. Create a file called hello_http.go in the gcf_hello_world directory with the following contents:

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"encoding/json"
    	"fmt"
    	"html"
    	"net/http"
    )
    
    // 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))
    }
    

    This example function takes a name supplied in the HTTP request and returns a greeting, or "Hello, World!" when no name is supplied.

Specifying dependencies

This example function only uses Go standard library packages, so you don't need to declare any dependencies beyond just importing the packages.

For functions that require dependencies outside of the standard library, you must provide the dependencies via either a go.mod file or a vendor directory. For more details, read Specifying dependencies in Go.

Deploying the function

To deploy the function with an HTTP trigger, run the following command in the gcf_hello_world directory, specifying either go113 or go111 as the value for the --runtime flag, depending on which version you are using:

gcloud functions deploy HelloHTTP --runtime go113 --trigger-http

Testing the function

  1. When the function finishes deploying, take note of the httpsTrigger.url property or find it using the following command:

    gcloud functions describe HelloHTTP
    

    It should look like this:

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP
  2. Visit this URL in your browser, or use cURL by running the command:

    curl https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP

    You should see a "Hello, World!" message. Try passing a name in the HTTP request by running the following command:

    curl -X POST https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP -H "Content-Type:application/json"  -d '{"name":"NAME"}'

    You should see the message "Hello, NAME!"

Viewing logs

Using the command-line tool

Logs for Cloud Functions are viewable in the Stackdriver Logging UI, and via the gcloud command-line tool.

To view logs for your function with the gcloud tool, use the logs read command, followed by the name of the function:

gcloud functions logs read HelloHTTP

The output should resemble the following:

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

Using the Logging dashboard

You can also view logs for Cloud Functions from the Cloud Console.

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Functions Documentation