猿问

如何在私有存储库中使用带有依赖项的 Go 运行 Google Cloud Function?

我正在尝试将本教程中的 Go 示例改编为在私有存储库中使用依赖项的内容。以下是 Cloud Function 示例代码:


package helloworld


import (

    "context"

    "log"


    "github.com/kurtpeek/my-private-repo/mypackage"

)


// PubSubMessage is the payload of a Pub/Sub event.

type PubSubMessage struct {

    Data []byte `json:"data"`

}


// HelloPubSub2 consumes a Pub/Sub message.

func HelloPubSub2(ctx context.Context, m PubSubMessage) error {

    name := string(m.Data)

    if name == "" {

        name = "World"

    }

    log.Printf("Hello, %s!", name)

    log.Println(mypackage.SayHello())

    return nil

}

在SayHello()私人回购中定义github.com/kurtpeek/my-private-repo为


package mypackage


// SayHello says hello

func SayHello() string {

    return "Hello, world!"

}

如果不调用mypackage.SayHello(),Cloud Function 将按预期部署和运行。我也可以在跑步HelloPubSub2后main.go跑步


git config url."git@github.com".insteadOf "https://github.com"

并将我的 SSH 密钥添加到存储库(参见这篇Medium 文章)。


但是,如果我尝试使用mypackage.SayHello(),我会收到以下错误:


无法读取“ https://github.com ”的用户名


这是完整的终端输出:


gcloud functions deploy HelloPubSub2 --runtime go113 --trigger-topic mytopic

Created .gcloudignore file. See `gcloud topic gcloudignore` for details.

WARNING: Function created with limited-access IAM policy. To enable unauthorized access consider "gcloud alpha functions add-iam-policy-binding HelloPubSub2 --member=allUsers --role=roles/cloudfunctions.invoker"

Deploying function (may take a while - up to 2 minutes)...failed.                                              

部署此 Cloud Function 的最佳方式是什么?我应该运行go mod vendor然后更改依赖项以引用vendor/目录吗?(不过,这似乎每次都做起来很麻烦)。


杨魅力
浏览 102回答 1
1回答

largeQ

我在此处以及尝试使用 go modules 在 Go 1.11 中部署 Google 云功能时遇到了答案(由从事此产品工作的 Google 工程师提供)。关键是gcloud functions deploy只将运行它的目录的内容复制到 Cloud Function 的“上下文”中,因此该vendor/目录必须在该目录中。同时,我注意到packagecannot be main,所以我采取了一些不寻常的步骤,go.mod从 repo 的根目录中删除并在目录中运行go mod initand 。现在它起作用了:go mod vendorhelloworld> gcloud functions deploy HelloPubSub2 --runtime go113 --trigger-topic mytopicDeploying function (may take a while - up to 2 minutes)...done.                                                         availableMemoryMb: 256entryPoint: HelloPubSub2eventTrigger:...
随时随地看视频慕课网APP

相关分类

Go
我要回答