This tutorial guides you through developing and deploying community Cloud Functions using Go: setting up your project and enabling the Cloud Functions API. Write a Go function and create a file containing the code. Compile and deploy functions. Test functions using cURL. Handle errors and return appropriate response codes.
Community tutorial for Go function development
This tutorial will guide you to understand how to use the Go language to develop functions and deploy them to Community runtime environment. We'll walk through the process step by step and provide a practical case so you can experience it for yourself.
Prerequisites
Step 1: Set up a Cloud Functions project
Create a new Google Cloud project:
gcloud projects create my-functions-project
Enable Cloud Functions API:
gcloud services enable cloudfunctions.googleapis.com
Step 2: Write the Go function
Create A file named hello_world.go
and enter the following code:
package main import ( "context" "fmt" "log" "github.com/cloudevents/sdk-go/v2/event" ) func HelloFunction(ctx context.Context, e event.Event) error { msg := e.Data() if msg != nil { s := string(msg) log.Printf("Function invoked with data: %s", s) return fmt.Errorf("function failed with message: %s", s) } msg = []byte("Hello World!") log.Print("Function invoked without data") return e.Respond(200, msg, event.ResultOK) }
Step 3: Compile and deploy the function
Compile your function:
go build hello_world.go
Deploy your function:
gcloud functions deploy hello_world \ --runtime go113 \ --entry-point HelloFunction \ --trigger-http \ --service-account my-service-account@my-functions-project.iam.gserviceaccount.com
Step 4: Test your function
Test your function using cURL:
curl https://<REGION>-<PROJECT_ID>.cloudfunctions.net/hello_world
You should see the response "Hello World!".
Step 5: Handling Errors
Our earlier example function returned an error when it received invalid data. We can check if the data exists by looking at the type of e.Data()
:
if e.Data() == nil { return e.Respond(400, nil, event.ResultFailedPrecondition) }
The above is the detailed content of Community tutorial on golang function development. For more information, please follow other related articles on the PHP Chinese website!