![](/img/trans.png)
[英]How to call a Dataflow job written in Go from Cloud Functions in GCP
[英]How to call a Go Cloud Function from another Go Cloud Function in GCP
目標:我想通過 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/ 部分。
其他較小的問題:我想重用的函數可能都在同一個文件中,並且不需要任何觸發器,但似乎沒有觸發器是不可能的。
我無法實現目標的相關問題和文檔:
很可能在控制台中定義的每個雲 function 是相互獨立的。 如果你想要代碼重用,最好按照下面的文檔來組織它,並使用 gcloud 命令部署它。
https://cloud.google.com/functions/docs/writing/#structuring_source_code
您正在混合:package 管理和 function 部署。
當您部署雲 Function 時,如果您想(重新)使用它,您必須使用 http package 調用 if。
如果您構建一個 package 並希望包含在您的源代碼中,您必須依賴 package 管理器。 With Go, Git repository, like Github, is the best way to achieve this (Don't forget to perform a release and to name it as expected by Go mod: vX.YZ)
如果沒有更多的工程和 package 發布/管理,您的代碼將無法運行。
我實現了相同的目標,但使用 Dockerfile 並且我對 Cloud Run 中的代碼感到遺憾(如果您不是面向事件且僅面向 HTTP,我建議您這樣做。我在 Medium 上寫了一個比較)
在我的helloworld.go
中,我可以重用 package 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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.