gcp cloud function returns 404 when deployed from command line

Issue

If I deploy the example hello world within the console, the url/trigger works. If I deploy from command line it looks to be exact same code / attributes in cloud functions console, but the url is 404. I can’t spot the difference/issue.

The deployed trigger/url shows – "404 page not found" for the below hello world example if deployed this way from command line.

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))
}

Solution

Thanks all, my project where I got stuck has more code in it than just this function. I went down this path after trying to deploy a single function/file within larger project. If I simplify down to a folder with just a hello.go and go.mod indeed it works :-/ to deploy it from command line:

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

Thank you for the fast replies and assistance. Rather than try to create a single function within existing project with larger go.sum, multiple folders, existing server/api etc. I am going to start from here having a single file with a cloud function and build on top of it and see at what point/if I get stuck again.

Answered By – Nick Foden

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.