当源代码包含多个级别/目录时部署 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 控制台中函数详细信息的源选项卡)。因此该函数无法部署,因为显然使用了.entrypoint.gomodule1/module1.go


如果源是.zipGoogle Cloud Storage 上的一个(包含多个目录),也会发生同样的情况:


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!"

}


手掌心
浏览 100回答 1
1回答

富国沪深

OK. It works for me with some changes.I'm using GOPATH and so am prefixing with GO111MODULE=on. If you are outside of GOPATH, I think you can just drop the GO111MODULE=on environment setting.Starting with directories and .go files only (no .mod files).My path is github.com/DazWilkin/cloudfuncs.IIUC you will need to -- minimally -- prefix module paths with example.com.package functionimport (    "fmt"    "net/http"    "github.com/DazWilkin/cloudfuncs/shared")func HelloFreddie(w http.ResponseWriter, r *http.Request) {    fmt.Fprint(w, shared.Hello())}Then, from within my cloudfuncs directory:GO111MODULE=on go mod init github.com/DazWilkin/testResults in a go.mod:module github.com/DazWilkin/cloudfuncsgo 1.11There is no go.mod file in .../cloudfuncs/shared.Then I deploy using:gcloud functions deploy HelloFreddie \--region=us-central1 \--entry-point=HelloFreddie \--runtime=go111 \--source=$PWD/cloudfuncs \--project=${PROJECT} \--trigger-httpYou can see the result here: https://us-central1-dazwilkin-190225-54842789.cloudfunctions.net/HelloFreddie
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go