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

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

我尝试过的方法和重现该问题的步骤:

  1. 在GCP中,创建一个新的Go 1.11 Cloud Function 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. How can I use a sub-packages with Go on Google Cloud Functions?
  2. https://github.com/golang/go/wiki/Modules的go.mod部分
jjyinhua 回答:如何从GCP中的另一个Go Cloud函数调用Go Cloud函数

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

因此,如果要使用无法从程序包管理器下载的依赖项来部署功能,则需要像here这样的代码放在一起,并使用CLI

进行部署 ,

控制台中定义的每个云功能很可能彼此独立。如果要重复使用代码,最好按照以下文档进行结构化,并使用gcloud命令进行部署。

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

,

您正在混合使用:软件包管理和功能部署。

部署云功能时,如果要(重新)使用它,则必须使用http软件包进行调用。

如果要构建要包含在源代码中的软件包,则必须依靠软件包管理器。使用Go,像Github一样,Git存储库是实现此目标的最佳方法(别忘了执行发布并按Go mod的名称命名:vX.Y.Z)

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

我用Dockerfile达到了相同的目的,并且对Cloud Run中的代码感到沮丧(如果您不是面向事件的,并且仅面向HTTP,我建议您。我写了comparison on Medium

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

本文链接:https://www.f2er.com/3155405.html

大家都在问