如何从GCP中的另一个Go Cloud函数调用Go Cloud函数



目标:我想重用两个带有HTTP触发器的Go函数中的许多Go函数。

我所尝试的以及重现问题的步骤:

  1. 在GCP中,创建一个新的Go 1.11云函数,HTTP触发器
  2. 名称:MyReusableHelloWorld
  3. function.go中,粘贴以下内容:
package Potatoes
import (   
"net/http"
)

// Potatoes return potatoes
func Potatoes(http.ResponseWriter, *http.Request) {
}
  1. go.mod中,粘贴以下内容:module example.com/foo
  2. 在要执行的函数中,粘贴以下内容:Potatoes
  3. 单击部署。它有效
  4. 在GCP中创建另一个Go无服务器函数
  5. 功能中。去,粘贴这个:
// 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))
}
  1. go.mod中,粘贴以下内容:module example.com/foo
  2. 在要执行的函数中,粘贴以下内容:HelloWorld
  3. 单击部署它不起作用您有错误:unknown import path "example.com/foo/Potatoes": cannot find module providing package example.com/foo/Potatoes

我还尝试了要导入的模块/包的各种组合。我试过没有example.com/部分。

其他较小的问题:我想要重用的函数可能都在同一个文件中,并不需要任何触发器,但似乎不可能没有触发器。

我无法实现目标的相关问题和文档:

  1. 如何在谷歌云功能上使用Go子包
  2. https://github.com/golang/go/wiki/Modules,截面go.mod

您不能从另一个调用云函数,因为每个函数都独立地位于自己的容器中。

因此,如果您想部署具有无法从包管理器下载的依赖项的函数,您需要像这里一样将代码放在一起,并使用CLI 进行部署

控制台中定义的每个云函数很可能彼此独立。如果您想重用代码,最好按照下面的文档构建代码,并使用gcloud命令进行部署。

https://cloud.google.com/functions/docs/writing/#structuring_source_code

您正在混合:包管理和功能部署。

当你部署一个云函数时,如果你想(重新(使用它,你必须用http包调用if。

如果您构建了一个要包含在源代码中的包,则必须依赖包管理器。有了Go,Git存储库,就像Github一样,是实现这一目标的最佳方式(别忘了执行发布并按照Go mod:vX.Y.Z的预期命名(

在这里,如果没有更多的工程和包发布/管理,您的代码就无法工作。

我实现了同样的事情,但使用了Dockerfile,我对我在Cloud Run中的代码表示遗憾(如果你不是面向事件的,而只是面向HTTP的,我建议你这样做。我在Medium上写了一个比较(

    • go.mod
    • pkg/foo.go
    • pkg/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 service/Helloworld.go

最新更新