使用 Go 创建和部署 HTTP Cloud Functions 函数

使用 Go 创建和部署 HTTP Cloud Functions 函数

简介

本指南将引导您完成用 Go 运行时编写 Cloud Functions 函数的过程。Cloud Functions 函数有两种类型:

  • HTTP 函数,通过标准 HTTP 请求调用。
  • 事件驱动型函数,由云基础设施中的事件触发,例如 Pub/Sub 主题中收到消息或 Cloud Storage 存储桶发生更改。

如需了解详情,请参阅编写 HTTP 函数编写事件驱动型函数

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  3. 确保您的 Google Cloud 项目已启用结算功能

  4. 启用 Cloud Functions、Cloud Build、Artifact Registry、Cloud Run 和 Cloud Logging API。

    启用 API

  5. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  6. 确保您的 Google Cloud 项目已启用结算功能

  7. 启用 Cloud Functions、Cloud Build、Artifact Registry、Cloud Run 和 Cloud Logging API。

    启用 API

  8. 安装并初始化 gcloud CLI
  9. 使用以下命令更新和安装 gcloud 组件。
    gcloud components update
  10. 准备开发环境。

    转到 Go 设置指南

创建函数

  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.mod 文件来跟踪您的依赖项:

cd ~/helloworld
go mod init example.com/hello
go mod tidy

如果您的函数具有除 Functions 框架库之外的依赖项,请修改 go.mod 文件以添加它们。您还可以使用 Go vendor 目录指定依赖项。如需了解详情,请参阅指定 Go 依赖项

在本地构建和测试函数

您可以选择在本地构建和测试函数,而无需部署该函数。为此,您必须创建一个本地 main.go 模块来调用您的函数。

  1. 创建 cmd 子目录:

    mkdir ~/helloworld/cmd
    cd ~/helloworld/cmd
    
  2. 将以下代码段复制到 ~/helloworld/cmd 目录中名为 main.go 的文件中,从而创建一个主 Go 模块以调用您的函数:

    package main
    
    import (
      "log"
      "os"
    
      // Blank-import the function package so the init() runs
      _ "example.com/hello"
      "github.com/GoogleCloudPlatform/functions-framework-go/funcframework"
    )
    
    func main() {
      // Use PORT environment variable, or default to 8080.
      port := "8080"
      if envPort := os.Getenv("PORT"); envPort != "" {
        port = envPort
      }
      if err := funcframework.Start(port); err != nil {
        log.Fatalf("funcframework.Start: %v\n", err)
      }
    }
    
  3. 使用 go mod tidy 命令解析其余依赖项:

    go mod tidy
    
  4. 使用以下命令在本地运行函数:

    export FUNCTION_TARGET=HelloHTTP
    go run ~/helloworld/cmd/main.go
    
  5. 在浏览器中访问 http://localhost:8080,或从其他窗口运行 curl localhost:8080,以测试函数。

    如需了解详情,请参阅向本地函数发送请求

部署函数

如需部署函数,请在 helloworld 目录中运行以下命令:

  gcloud functions deploy go-http-function \
    --gen2 \
    --runtime=go121 \
    --region=REGION \
    --source=. \
    --entry-point=HelloHTTP \
    --trigger-http \
    --allow-unauthenticated

REGION 替换为要部署函数的 Google Cloud 区域的名称(例如 us-west1)。

通过可选的 --allow-unauthenticated 标志,您可以在不进行身份验证的情况下访问函数。

测试已部署的函数

  1. 函数部署后,请记下 gcloud functions deploy 命令输出中的 uri 属性,或使用以下命令检索该属性:

      gcloud functions describe go-http-function \
        --region=REGION
    

    REGION 替换为您在其中部署函数的 Google Cloud 区域的名称(例如 us-west1)。

  2. 在浏览器中访问此网址。该函数将返回一条“Hello World!”消息。

    您还可以在 Google Cloud 控制台中找到此网址。转到 Cloud Functions 概览页面,点击函数的名称以打开其函数详情页面。打开触发器标签页以查看函数的网址。

查看函数日志

使用命令行工具查看日志

您可以使用 Cloud Logging 界面或通过 Google Cloud CLI 查看函数的日志。

如需使用 gcloud CLI 查看函数的日志,请使用 logs read 命令:

    gcloud functions logs read \
      --gen2 \
      --limit=10 \
      --region=REGION \
      go-http-function

REGION 替换为您在其中部署函数的 Google Cloud 区域的名称(例如 us-west1)。

输出类似以下内容:

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-05-31 21:52:20.473
LOG:

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-05-31 21:52:20.370
LOG:

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-05-31 21:52:20.280
LOG: Default STARTUP TCP probe succeeded after 1 attempt for container "h-hello_h_t_t_p-1" on port 8080.

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-05-31 21:52:20.108
LOG:

使用日志记录信息中心查看日志

要使用日志记录信息中心查看函数的日志,请打开 Cloud Functions 概览页面,点击列表中的函数名称,然后点击日志标签页。