如何从GCP中的另一个Go Cloud函数调用Go Cloud函数 [英] How to call a Go Cloud Function from another Go Cloud Function in GCP
问题描述
目标:我想重用带有HTTP触发器的两个Go函数中的许多Go函数.
Goal: I want to reuse many Go functions from two Go functions with HTTP triggers.
我尝试过的方法和重现该问题的步骤:
- 在GCP中,创建一个新的Go 1.11 Cloud Function HTTP触发器
- 命名:
MyReusableHelloWorld
- 在
function.go
中,粘贴以下内容:
- In GCP, create a new Go 1.11 Cloud Function, HTTP Trigger
- Name it:
MyReusableHelloWorld
- In
function.go
, paste this:
package Potatoes
import (
"net/http"
)
// Potatoes return potatoes
func Potatoes(http.ResponseWriter, *http.Request) {
}
- 在
go.mod
中,粘贴以下内容:module example.com/foo
- 在要执行的函数中,粘贴以下内容:
Potatoes
- 单击部署.可以.
- 在GCP中创建另一个Go无服务器功能
- 在功能上.去,粘贴这个:
- In
go.mod
, paste this:module example.com/foo
- In function to execute, paste this:
Potatoes
- Click on deploy. It works.
- Create another Go serverless function in GCP
- In function. go, paste this:
// 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
- In
go.mod
, paste this:module example.com/foo
- In function to execute, paste this:
HelloWorld
- Click on deploy. It doesn't work. You have the error:
unknown import path "example.com/foo/Potatoes": cannot find module providing package example.com/foo/Potatoes
我还尝试了各种组合来导入模块/软件包. 我尝试过没有example.com/部分.
I have also tried all kinds of combinations for the module/packages to import. I have tried without the example.com/ part.
其他较小的问题: 我想重用的功能可能全部在同一个文件中,并且实际上并不需要任何触发器,但是似乎没有触发器是不可能的.
Other smaller issue: The functions I want to reuse could all be in the same file and don't really need any trigger, but it doesn't seem that having no trigger is possible.
我无法实现目标的相关问题和文档:
- How can I use a sub-packages with Go on Google Cloud Functions?
- https://github.com/golang/go/wiki/Modules , section go.mod
推荐答案
您不能从另一个调用云功能,因为每个功能都独立地位于其自己的容器中.
You can’t invoke a cloud function from another one, because each function is in its own container independently.
因此,如果您要部署具有无法从程序包管理器下载的依赖项的功能,则需要将代码放在一起,例如 CLI
So If you want to deploy the function with a dependency that can't be downloaded from a package manager you need to put the code together like here and deploy using the CLI
这篇关于如何从GCP中的另一个Go Cloud函数调用Go Cloud函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!