Goal:我想使用HTTP触发器重用两个Go函数中的许多Go函数。
我尝试过的方法和重现此问题的步骤:
MyReusableHelloWorld
function.go
中,粘贴此:package Potatoes
import (
"net/http"
)
// Potatoes return potatoes
func Potatoes(http.ResponseWriter, *http.Request) {
}
go.mod
中,粘贴此:module example.com/foo
Potatoes
// 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))
}
go.mod
中,粘贴此:module example.com/foo
HelloWorld
unknown import path "example.com/foo/Potatoes": cannot find module providing package example.com/foo/Potatoes
我还尝试了各种组合来导入模块/软件包。我尝试过没有example.com/部分。
其他较小的问题:我想重用的功能可能全部在同一个文件中,并且实际上并不需要任何触发器,但是似乎没有触发器是不可能的。
我无法实现目标的相关问题和文档:
[控制台中定义的每个云功能都可能彼此独立。如果要重复使用代码,则最好按照以下文档进行结构化,并使用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)
在我的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
。