functions-framework-go

repository·main·Indexed 19 days ago

https://github.com/googlecloudplatform/functions-framework-go

An open source FaaS (Function as a Service) framework for writing portable Go functions. It supports deployment on Google Cloud Run functions, Knative, App Engine, or local environments. The framework provides support for HTTP functions, CloudEvent functions, and background event functions, and includes features like execution ID logging via LogWriter.

Tokens
1.4K
Snippets
6
Records
6
Agent score
18%

What's inside functions-framework-go

  1. Quickstart: Run a Hello World function locally

    main

    To run a Go function on your local machine, follow these steps:

    1. Initialize the module:

      go mod init example.com/hello
    2. Create your function: Create a function.go file. Use the functions.HTTP method in an init() function to register your handler.

    3. Create a local runner: Since the framework is designed for serverless environments, you need a main package to run it locally. Create a cmd/main.go file that uses funcframework.StartHostPort to start the server. Use the FUNCTION_TARGET environment variable to specify which function to run.

    4. Run the server:

      FUNCTION_TARGET=HelloWorld LOCAL_ONLY=true go run cmd/main.go
    5. Test the function:

      curl localhost:8080
    // function.go
    package function
    
    import (
    	"fmt"
    	"net/http"
    
    	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
    )
    
    func init() {
    	functions.HTTP("HelloWorld", helloWorld)
    }
    
    func helloWorld(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprintln(w, "Hello, World!")
    }
  2. Enable Execution ID logging

    main

    To enable execution ID logging (useful for filtering logs in Cloud Run Functions), you have two options:

    1. Via HTTP Header: Provide a custom execution ID in the Function-Execution-Id header of your request.

      curl -H "Function-Execution-Id: 123456" localhost:8080
    2. Via LogWriter: Use funcframework.LogWriter (available in v1.9.0+) to generate logs. If the Function-Execution-Id header is missing, the framework will automatically generate a pseudo-random execution ID for the logs.

    // Using LogWriter to automatically include execution IDs
    func helloWorld(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!")
    }
  3. Build a deployable container using Buildpacks

    main

    You can build a production-ready container image from your function using Google Cloud Buildpacks and the pack CLI tool. This avoids the need to write a manual main.go for deployment.

    Use the following command, ensuring you set the GOOGLE_FUNCTION_SIGNATURE_TYPE and GOOGLE_FUNCTION_TARGET environment variables:

    pack build \
    	--builder gcr.io/buildpacks/builder:v1 \
    	--env GOOGLE_FUNCTION_SIGNATURE_TYPE=http \
    	--env GOOGLE_FUNCTION_TARGET=HelloWorld \
    	my-first-function
  4. Implement CloudEvent Functions

    main

    CloudEvent functions allow you to unmarshal incoming CloudEvents into a cloudevents.Event object. These are registered using functions.CloudEvent(name, handler). The handler signature must be func(context.Context, cloudevents.Event) error.

    package function
    
    import (
    	"context"
    	cloudevents "github.com/cloudevents/sdk-go/v2"
    	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
    )
    
    func init() {
    	functions.CloudEvent("CloudEventFunc", cloudEventFunc)
    }
    
    func cloudEventFunc(ctx context.Context, e cloudevents.Event) error {
    	// Access event data via e.DataAs(targetStruct)
    	return nil
    }
  5. Implement Background Event Functions

    main

    Background event functions handle events like Pub/Sub or GCS triggers. The handler signature is func(context.Context, T) error, where T is a user-defined struct containing the event data fields.

    To access event metadata (like event ID or timestamp) from the context, use the cloud.google.com/go/functions/metadata package with metadata.FromContext(ctx).

    func BackgroundEventFunction(ctx context.Context, data userDefinedEventStruct) error {
    	// Do something with ctx and data
    	return nil
    }
  6. Implement HTTP Functions

    main

    HTTP functions are the most common type. They use the standard http.ResponseWriter and *http.Request signatures. Register them using functions.HTTP(name, handler) within an init() function.

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