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

问题描述 投票:0回答:3

Goal:我想使用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节
go google-cloud-platform serverless
3个回答
0
投票

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

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


0
投票

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

[部署云功能时,如果要(重新)使用它,则必须使用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


0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.