Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

FaaS (Function as a service) framework for writing portable Go functions

License

NotificationsYou must be signed in to change notification settings

GoogleCloudPlatform/functions-framework-go

Repository files navigation

GoDocGo version

Go unit CIGo lint CIGo conformace CISecurity Scorecard

An open source FaaS (Function as a Service) framework for writing portableGo functions.

The Functions Framework lets you write lightweight functions that run in manydifferent environments, including:

The framework allows you to go from:

funcHelloWorld(w http.ResponseWriter,r*http.Request) {fmt.Fprint(w,"Hello, World!")}

To:

curl http://my-url# Output: Hello, World!

All without needing to worry about writing an HTTP server or requesthandling logic.

Features

  • Build your Function in the same container environment used by Cloud Run functions usingbuildpacks.
  • Invoke a function in response to a request
  • Automatically unmarshal events conforming to theCloudEvents spec
  • Portable between serverless platforms

Quickstart: Hello, World on your local machine

  1. Install Go 1.18+.

  2. Create a Go module:

    go mod init example.com/hello

    Note: You can use a different module name rather thanexample.com/hello.

  3. Create afunction.go file with the following contents:

    package functionimport ("fmt""net/http""github.com/GoogleCloudPlatform/functions-framework-go/functions")funcinit() {functions.HTTP("HelloWorld",helloWorld)}// helloWorld writes "Hello, World!" to the HTTP response.funchelloWorld(w http.ResponseWriter,r*http.Request) {fmt.Fprintln(w,"Hello, World!")}

    Note that you can use any file name or package name (convention is to makepackage name same as directory name).

  4. To run locally, you'll need to create a main package to start your server(see instructions below for container builds to skip this step and match yourlocal development environment to production):

    mkdir cmd
  5. Create acmd/main.go file with the following contents:

    package mainimport ("log""os"// Blank-import the function package so the init() runs_"example.com/hello""github.com/GoogleCloudPlatform/functions-framework-go/funcframework")funcmain() {// Use PORT environment variable, or default to 8080.port:="8080"ifenvPort:=os.Getenv("PORT");envPort!="" {port=envPort}// By default, listen on all interfaces. If testing locally, run with// LOCAL_ONLY=true to avoid triggering firewall warnings and// exposing the server outside of your own machine.hostname:=""iflocalOnly:=os.Getenv("LOCAL_ONLY");localOnly=="true" {hostname="127.0.0.1"}iferr:=funcframework.StartHostPort(hostname,port);err!=nil {log.Fatalf("funcframework.StartHostPort: %v\n",err)}}
  6. Rungo mod tidy to update dependency requirements.

  7. Start the local development server:

    FUNCTION_TARGET=HelloWorld LOCAL_ONLY=true go run cmd/main.go# Output: Serving function: HelloWorld

    Upon starting, the framework will listen to HTTP requests at/ and invoke your registered functionspecified by theFUNCTION_TARGET environment variable (i.e.FUNCTION_TARGET=HelloWorld).

  8. Send requests to this function usingcurl from another terminal window:

    curl localhost:8080# Output: Hello, World!

Quickstart: Enable Exeuction Id Logging

Cloud Run Functions(1st gen) provides an execution id in the logs atlabels.execution_id, which customers can use to filter their logs for each execution.Cloud Run Functions doesn't have the same feature embedded.

To have exeuction id logged forCloud Run Functions executions, users can either:

  • Provide a custom execution Id in the Http HeaderFunction-Execution-Id.

     curl -H"Function-Execution-Id: 123456" localhost:8080# Output: Hello, World!

    Example Log:

     {"message":"Try logging with executionID!","logging.googleapis.com/labels":{"execution_id":"123456"}}

OR

  • LeverageLogWriter provided in function-framework-go(v1.9.0 or higher) library to generate logs. IfFunction-Exeuction-Id is empty, a pseduorandom execution id will be auto-generated ifLogWriter is used.

    package functionimport ("fmt""net/http""log""github.com/GoogleCloudPlatform/functions-framework-go/functions""github.com/GoogleCloudPlatform/functions-framework-go/funcframework" )funcinit() {functions.HTTP("HelloWorld",helloWorld) }// helloWorld writes "Hello, World!" to the HTTP response.funchelloWorld(w http.ResponseWriter,r*http.Request) {l:=log.New(funcframework.LogWriter(r.Context()),"",0)l.Println("Try logging with executionID!")fmt.Fprintln(w,"Hello, World!") }

    Example Log:

     {"message":"Try logging with executionID!","logging.googleapis.com/labels":{"execution_id":"181dbb5b096549313d470dd68fa64d96"}}

Go further: build a deployable container

  1. InstallDocker and thepack tool.

  2. Build a container from your function using the Functionsbuildpacks:

    pack build \--builder gcr.io/buildpacks/builder:v1 \--env GOOGLE_FUNCTION_SIGNATURE_TYPE=http \--env GOOGLE_FUNCTION_TARGET=HelloWorld \my-first-function
  3. Start the built container:

    docker run --rm -p 8080:8080 my-first-function# Output: Serving function...
  4. Send requests to this function usingcurl from another terminal window:

    curl localhost:8080# Output: Hello, World!

Run your function on serverless platforms

Google Cloud Run functions

Deploy from your local machine using thegcloud command-line tool.Check out the Cloud Functions quickstart.

Container environments based on Knative

The Functions Framework is designed to be compatible with Knative environments.Just build and deploy your container to a Knative environment. Note that your app needs to listenPORT environment variable perKnative runtime contract.

Functions Framework Features

The Go Functions Framework conforms to theFunctions Framework Contract, As such, itsupports HTTP functions, background event functions, and CloudEvent functions(as of v1.1.0). The primary build mechanism is theGCP buildpacks stack, which takes a function ofone of the accepted types, converts it to a full HTTP serving app, and creates alaunchable container to run the server.

HTTP Functions

The Framework provides support for handling native Go HTTP-style functions:

package functionimport ("net/http""github.com/GoogleCloudPlatform/functions-framework-go/functions")funcinit() {functions.HTTP("HelloWorld",helloWorld)}funchelloWorld(w http.ResponseWriter,r*http.Request) {w.Write([]byte("Hello, World!"))}

CloudEvent Functions

The Functions Framework provides support for unmarshalling an incomingCloudEvent payload into acloudevents.Event object.These will be passed as arguments to your function when it receives a request.

package functionimport (cloudevents"github.com/cloudevents/sdk-go/v2""github.com/GoogleCloudPlatform/functions-framework-go/functions")funcinit() {functions.CloudEvent("CloudEventFunc",cloudEventFunc)}funccloudEventFunc(ctx context.Context,e cloudevents.Event)error {// Do something with event.Context and event.Data (via event.DataAs(foo)).returnnil}

These functions are registered with the handler viafuncframework.RegisterCloudEventFunctionContext.

To learn more about CloudEvents, see theGo SDK for CloudEvents.

Background Event Functions

Background eventsare also supported. This type of function takes two parameters: a Go context anda user-defined data struct.

funcBackgroundEventFunction(ctx context.Context,datauserDefinedEventStruct)error {// Do something with ctx and data.}

This type of event requires you to define a struct with theappropriate data fields (e.g. those for a PubSub message or GCS event) and passthat struct as the data parameter. See thesamples for details.

The context parameter is a Gocontext.Context, and contains additional eventmetadata under a functions-specific key. This data is accesible via thecloud.google.com/go/functions/metadata package:

m:=metadata.FromContext(ctx)

These functions can be registered inmain.go for local testing with the handler viafuncframework.RegisterEventFunctionContext.


[8]ページ先頭

©2009-2025 Movatter.jp