簡體   English   中英

如何從另一個 Go 雲 Z86408593C34AF77FDD90ZDF932F 調用 Go 雲 Function

[英]How to call a Go Cloud Function from another Go Cloud Function in GCP

目標:我想通過 HTTP 觸發器重用來自兩個 Go 函數的許多 Go 函數。

我嘗試過的方法和重現問題的步驟:

  1. 在 GCP 中,新建 Go 1.11 雲 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. 在 function 執行,粘貼這個: Potatoes
  3. 點擊部署。 有用。
  4. 在 GCP 中創建另一個 Go 無服務器 function
  5. 在 function 中。 go,粘貼這個:
// 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. 在 function 中執行,粘貼: HelloWorld
  3. 點擊部署。 它不起作用。 您有錯誤: unknown import path "example.com/foo/Potatoes": cannot find module providing package example.com/foo/Potatoes

我還嘗試了各種組合來導入模塊/包。 我試過沒有 example.com/ 部分。

其他較小的問題:我想重用的函數可能都在同一個文件中,並且不需要任何觸發器,但似乎沒有觸發器是不可能的。

我無法實現目標的相關問題和文檔:

  1. 如何在 Google Cloud Functions 上使用帶有 Go 的子包?
  2. https://github.com/golang/go/wiki/Modules部分 go.mod

您不能從另一個雲調用 function,因為每個 function 都獨立地在自己的容器中。

因此,如果您想部署 function 具有無法從 package 管理器下載的依賴項,您需要像此處一樣將代碼放在一起並使用CLI進行部署

很可能在控制台中定義的每個雲 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 上寫了一個比較

    • go.mod
    • 包/foo.go
    • 包/go.mod
    • 服務/Helloworld.go
    • 服務/go.mod

在我的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM