从命令行部署时,gcp 云函数 returns 404

gcp cloud function returns 404 when deployed from command line

如果我在控制台中部署 example hello world,url/trigger 会起作用。如果我从命令行部署,它看起来与云功能控制台中的代码/属性完全相同,但 url 是 404。我无法发现 difference/issue.

如果从命令行以这种方式部署,部署的 trigger/url 显示 - 对于下面的 hello world 示例,“找不到 404 页面”。

gcloud functions deploy hellogo --entry-point=HelloWorld --trigger-http --region=us-central1 --memory=128MB --runtime=go116 --allow-unauthenticated

// Package p contains an HTTP Cloud Function.
package p

import (
    "encoding/json"
    "fmt"
    "html"
    "io"
    "log"
    "net/http"
)

// 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 {
        switch err {
        case io.EOF:
            fmt.Fprint(w, "Hello World!")
            return
        default:
            log.Printf("json.NewDecoder: %v", err)
            http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
            return
        }
    }

    if d.Message == "" {
        fmt.Fprint(w, "Hello World!")
        return
    }
    fmt.Fprint(w, html.EscapeString(d.Message))
}

试图重现您的错误,但我无法重现。我使用了与您相同的命令,我可以成功访问 url 或通过 HTTP 触发调用已部署的 hello world 云函数。

gcloud functions deploy hellogo --entry-point=HelloWorld --trigger-http --region=us-central1 --memory=128MB --runtime=go116 --allow-unauthenticated

成功c的输出url:

我建议您检查您尝试访问的 url,因为根据此 GCP doc:

If you attempt to invoke a function that does not exist, Cloud Functions responds with an HTTP/2 302 redirect which takes you to the Google account login page. This is incorrect. It should respond with an HTTP/2 404 error response code. The problem is being addressed.

解决方案

Make sure you specify the name of your function correctly. You can always check using gcloud functions call which returns the correct 404 error for a missing function.

您也可以参考这个完整的 guide 以使用 Go 运行时快速开始您的 CF 创建和部署。

谢谢大家,我卡住的项目中的代码不仅仅是这个函数。在尝试在更大的项目中部署单个 function/file 之后,我走上了这条路。如果我简化为只有 hello.gogo.mod 的文件夹,它确实有效:-/ 从命令行部署它:

gcloud functions deploy hellogo --entry-point=HelloWorld --trigger-http --region=us-central1 --memory=128MB --runtime=go116 --allow-unauthenticated

// go.mod

module github.com/nickfoden/hello

go 1.16

感谢您的快速回复和帮助。而不是尝试在具有更大 go.sum、多个文件夹、现有 server/api 等的现有项目中创建单个函数。我将从这里开始,拥有一个具有云函数的单个文件并构建在看看是什么 point/if 我又卡住了。