当前位置: > > > > 当源代码包含多个级别/目录时部署 Google Cloud Function
当源代码包含多个级别/目录时部署 Google Cloud Function
来源:stackoverflow
2024-04-27 08:00:37
0浏览
收藏
今天米云给大家带来了《当源代码包含多个级别/目录时部署 Google Cloud Function》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~
问题内容
我想部署一个用 go 编写的 google cloud function,其代码结构包含一个子目录,如下所示:
function ├── module1 │ ├── go.mod │ └── module1.go ├── go.mod └── entrypoint.go
但是当我部署该功能时,使用 gcp 控制台或 gcloud 命令:
# from function/ directory gcloud functions deploy myfunction --runtime go111 [...]
仅上传 go.mod 和 entrypoint.go(我在 gcp console 中的函数详细信息的源选项卡上进行了检查)。因此该函数无法部署,因为显然 entrypoint.go 使用了 module1/module1.go 中的方法。
如果源是 google cloud storage 上的 .zip(包含多个目录),也会发生同样的情况:
gcloud functions deploy myfunction \
--runtime go111 \
--source gs://${bucket}/function.zip [...]
是否可以使用带有子目录的代码结构来部署函数?我不知道其他运行时(python、nodejs)是否也会发生同样的情况,或者问题是否是 go 特有的。
编辑
我尝试遵循本指南:https://cloud.google.com/functions/docs/writing/#functions-writing-file-structuring-go(第二点:根目录下的包正如评论中所建议的,从子包导入代码并导出一个或多个函数的项目),但没有成功。这是我使用的结构(在本地工作):
.
├── function.go
├── go.mod
└── shared
├── go.mod
└── shared.go
go.mod
module testcloudfunction require testcloudfunction/shared v0.0.0 replace testcloudfunction/shared => ./shared
函数.go
package function
import (
"fmt"
"testcloudfunction/shared"
)
func helloworld(w http.responsewriter, r *http.request) {
fmt.fprint(w, shared.hello())
}
共享/go.mod
module testcloudfunction/shared
共享/shared.go
package shared
func Hello() string {
return "Hello World!"
}
解决方案
好的。经过一些更改,它对我有用。
我正在使用 gopath,因此我使用 go111module=on 作为前缀。如果您位于 gopath 之外,我认为您可以删除 go111module=on 环境设置。
仅从目录和 .go 文件开始(无 .mod 文件)。
我的路径是 github.com/dazwilkin/cloudfuncs。
iiuc 您至少需要在模块路径前加上 example.com。
package function
import (
"fmt"
"net/http"
"github.com/dazwilkin/cloudfuncs/shared"
)
func hellofreddie(w http.responsewriter, r *http.request) {
fmt.fprint(w, shared.hello())
}
然后,从我的 cloudfuncs 目录中:
go111module=on go mod init github.com/dazwilkin/test
go.mod 的结果:
module github.com/dazwilkin/cloudfuncs go 1.11
.../cloudfuncs/shared 中没有 go.mod 文件。
然后我使用以下方式进行部署:
gcloud functions deploy HelloFreddie \
--region=us-central1 \
--entry-point=HelloFreddie \
--runtime=go111 \
--source=$PWD/cloudfuncs \
--project=${PROJECT} \
--trigger-http
您可以在此处查看结果:
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注米云公众号,一起学习编程~
