如何从GCP中的另一个Go Cloud函数调用Go Cloud函数
目标:我想使用HTTP触发器重用两个Go函数中的许多Go函数 我尝试的内容和重现问题的步骤:如何从GCP中的另一个Go Cloud函数调用Go Cloud函数,go,google-cloud-platform,serverless,Go,Google Cloud Platform,Serverless,目标:我想使用HTTP触发器重用两个Go函数中的许多Go函数 我尝试的内容和重现问题的步骤: 在GCP中,创建一个新的Go 1.11云函数HTTP触发器 命名:MyReusableHelloWorld 在function.go中,粘贴以下内容: 在go.mod中,粘贴以下内容:module example.com/foo 在要执行的函数中,粘贴以下内容:potations 单击deploy。它起作用了 在GCP中创建另一个Go无服务器功能 在功能上。去,粘贴这个: 在go.mod中,粘贴以下内容
MyReusableHelloWorld
function.go
中,粘贴以下内容:go.mod
中,粘贴以下内容:module example.com/foo
potations
go.mod
中,粘贴以下内容:module example.com/foo
HelloWorld
未知导入路径“example.com/foo/potates”:找不到提供包example.com/foo/potates的模块
控制台中定义的每个云函数很可能相互独立。如果希望代码重用,最好按照以下文档对其进行结构设计,并使用gcloud命令进行部署
您正在混合一些东西:包管理和功能部署 部署云函数时,如果要(重新)使用它,必须使用http包调用if 如果您构建了一个要包含在源代码中的包,那么您必须依赖于包管理器。有了Go,Git存储库(如Github)是实现这一点的最佳方式(不要忘记执行发布,并按照Go mod:vX.Y.Z的预期命名) 在这里,如果没有更多的工程和包发布/管理,代码将无法工作 我用Dockerfile实现了同样的目标,我对我在Cloud Run中的代码感到遗憾(如果你不是面向事件的,而只是面向HTTP的,我建议你这么做
- 根
- go.mod
- 包装/foo.go
- 包装/go.mod
- 服务/Helloworld.go
- 服务/go.mod
helloworld.go
中,我可以重用包foo
。为此,我在service/go.mod
文件中执行此操作
module service/helloworld
go 1.12
require pkg/foo v0.0.0
replace pkg/foo v0.0.0 => ../pkg
然后,当您构建容器时,您可以从根目录运行
go-build服务/Helloworld.go
。您不能从另一个云函数调用云函数,因为每个函数都独立地位于自己的容器中
因此,如果您想要部署具有无法从包管理器下载的依赖项的函数,则需要将代码放在一起,就像使用
// Package p contains an HTTP Cloud Function.
package p
import (
"encoding/json"
"fmt"
"html"
"net/http"
"example.com/foo/Potatoes"
)
// HelloWorld prints the JSON encoded "message" field in the body
// of the request or "Hello, World!" if there isn't one.
func HelloWorld(w http.ResponseWriter, r *http.Request) {
var d struct {
Message string `json:"message"`
}
if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
fmt.Fprint(w, "error here!")
return
}
if d.Message == "" {
fmt.Fprint(w, "oh boy Hello World!")
return
}
fmt.Fprint(w, html.EscapeString(d.Message))
}
module service/helloworld
go 1.12
require pkg/foo v0.0.0
replace pkg/foo v0.0.0 => ../pkg