发布于 2026-01-06 0 阅读
0

Go、Google Functions 和 Gitlab-ci 的完美组合 DEV 全球展示挑战赛,由 Mux 呈现:展示你的项目!

Go、Google Functions 和 GitLab CI 的完美组合

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

上周我用 Go 语言在GCP上测试了 Google Functions ,之后,我决定添加另一个我喜欢的服务——GitLab。我非常喜欢它,所以决定写这篇文章。

如果您知道如何在 GCP 上添加帐户进行部署,或者您已经拥有帐户,则可以忽略此部分。

创建 GitLab 帐户。

我会添加很多截图来解释清楚。
你需要访问 IAM 和管理员帐户,然后再访问服务帐户。
服务帐户

点击“+ 创建服务帐户”按钮
服务帐户

输入帐户名称以进行标识
服务帐户

您需要添加 3 个角色
服务帐户

创建密钥
服务帐户

确认已勾选 JSON 选项,然后点击创建按钮。
服务帐户


我们在 GCP 上完成了配置,现在我们将向存储库添加环境变量。PROJECT_ID 是项目的 ID,SERVICE_ACCOUNT 是您创建密钥时下载的内容。
服务帐户

好了,现在我们要编写代码来测试部署。我使用的是Google 的示例。
我们将创建 3 个文件,其中 hello_world.go 是函数。

// Package helloworld provides a set of Cloud Function 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!")
}
Enter fullscreen mode Exit fullscreen mode

hello_world_test.go 是该函数的测试文件。


package helloworld

import (
    "io/ioutil"
    "net/http/httptest"
    "strings"
    "testing"
)

func TestHelloGet(t *testing.T) {
    payload := strings.NewReader("")
    req := httptest.NewRequest("GET", "/", payload)

    rr := httptest.NewRecorder()
    HelloGet(rr, req)

    out, err := ioutil.ReadAll(rr.Result().Body)
    if err != nil {
        t.Fatalf("ReadAll: %v", err)
    }
    want := "Hello, World!"
    if got := string(out); got != want {
        t.Errorf("HelloWorld = %q, want %q", got, want)
    }
}
Enter fullscreen mode Exit fullscreen mode

以及用于运行持续集成的 .gitlab-ci.yml 文件。

image: google/cloud-sdk:alpine

test_production:
  image: golang:alpine
  stage: test
  only:
  - production
  script:
  - CGO_ENABLED=0 go test ./...

deploy_production:
  stage: deploy
  environment: Production
  only:
  - production
  script:
  - echo $SERVICE_ACCOUNT > /tmp/$CI_PIPELINE_ID.json
  - gcloud auth activate-service-account --key-file /tmp/$CI_PIPELINE_ID.json
  - gcloud --quiet --project $PROJECT_ID functions deploy HelloGet --runtime go111 --trigger-http
  after_script:
  - rm /tmp/$CI_PIPELINE_ID.json
Enter fullscreen mode Exit fullscreen mode

工作流程是,当我们在生产分支中合并更改时,这些操作将会运行。

就这样,正如你在下一张截图中看到的,部署已经完成,谷歌返回的结果也显示了已创建的网址。

服务帐户

就这些了,希望对你们有用=)。你们可以在仓库里看到代码。

文章来源:https://dev.to/renatosuero/go-google-functions-and-gitlab-ci-a-perfect-combination-4lao