### Start HTTP Server with Functions Framework in Go Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Use the `funcframework` package to start the HTTP server that serves registered functions. The server respects the `FUNCTION_TARGET` environment variable to route requests. Ensure your function package is blank-imported so its init() function runs. ```go package main import ( "log" "os" // Blank-import your function package so init() runs _ "example.com/myfunction" "github.com/GoogleCloudPlatform/functions-framework-go/funcframework" ) func main() { // Use PORT environment variable, or default to 8080 port := "8080" if envPort := os.Getenv("PORT"); envPort != "" { port = envPort } // For local development, bind to localhost only hostname := "" if localOnly := os.Getenv("LOCAL_ONLY"); localOnly == "true" { hostname = "127.0.0.1" } // Start the server if err := funcframework.StartHostPort(hostname, port); err != nil { log.Fatalf("funcframework.StartHostPort: %v\n", err) } } // Run with: // FUNCTION_TARGET=HelloWorld LOCAL_ONLY=true go run main.go // Output: Serving function: "HelloWorld" ``` -------------------------------- ### Basic Go Function Example Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md A minimal Go function that can be used with the Functions Framework. It demonstrates a simple HTTP response. ```Go func HelloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, World!") } ``` -------------------------------- ### Local Development Server for Go Functions Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md This main package starts the Functions Framework host, listening on a specified port. It requires blank-importing the function package to run its init() function. Use LOCAL_ONLY=true to restrict listening to localhost. ```Go package main import ( "log" "os" // Blank-import the function package so the init() runs _ "example.com/hello" "github.com/GoogleCloudPlatform/functions-framework-go/funcframework" ) func main() { // Use PORT environment variable, or default to 8080. port := "8080" if envPort := 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 := "" if localOnly := os.Getenv("LOCAL_ONLY"); localOnly == "true" { hostname = "127.0.0.1" } if err := funcframework.StartHostPort(hostname, port); err != nil { log.Fatalf("funcframework.StartHostPort: %v\n", err) } } ``` -------------------------------- ### Build Deployable Container with Pack CLI Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md Use the `pack` tool and Functions buildpacks to create a deployable container image for your Go function. Ensure Docker and `pack` are installed before running. ```sh pack build \ --builder gcr.io/buildpacks/builder:v1 \ --env GOOGLE_FUNCTION_SIGNATURE_TYPE=http \ --env GOOGLE_FUNCTION_TARGET=HelloWorld \ my-first-function ``` -------------------------------- ### Example HTTP Request to Local Function Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md This command sends an HTTP GET request to the locally running function. Ensure the FUNCTION_TARGET environment variable is set to the name of your registered function. ```Shell FUNCTION_TARGET=HelloWorld LOCAL_ONLY=true go run cmd/main.go ``` -------------------------------- ### Register HTTP and CloudEvent Functions with Context (Go) Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Use the context-based registration API to control function paths, useful for local testing with multiple functions. This example registers HTTP functions at `/api/hello` and `/api/users`, and CloudEvent functions at `/events` and `/background`. ```go package main import ( "context" "fmt" "log" "net/http" cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/GoogleCloudPlatform/functions-framework-go/funcframework" ) func main() { ctx := context.Background() // Register HTTP function at /api/hello if err := funcframework.RegisterHTTPFunctionContext(ctx, "/api/hello", helloHandler); err != nil { log.Fatalf("RegisterHTTPFunctionContext: %v", err) } // Register HTTP function at /api/users if err := funcframework.RegisterHTTPFunctionContext(ctx, "/api/users", usersHandler); err != nil { log.Fatalf("RegisterHTTPFunctionContext: %v", err) } // Register CloudEvent function at /events if err := funcframework.RegisterCloudEventFunctionContext(ctx, "/events", eventHandler); err != nil { log.Fatalf("RegisterCloudEventFunctionContext: %v", err) } // Register event function at /background if err := funcframework.RegisterEventFunctionContext(ctx, "/background", backgroundHandler); err != nil { log.Fatalf("RegisterEventFunctionContext: %v", err) } // Start server (without FUNCTION_TARGET, serves all registered paths) if err := funcframework.Start("8080"); err != nil { log.Fatalf("funcframework.Start: %v", err) } } func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello from /api/hello") } func usersHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, `{"users": [{"id": 1, "name": "Alice"}]}`) } func eventHandler(ctx context.Context, e cloudevents.Event) error { log.Printf("Received event: %s", e.Type()) return nil } type PubSubMessage struct { Data []byte `json:"data"` } func backgroundHandler(ctx context.Context, msg PubSubMessage) error { log.Printf("Received message: %s", string(msg.Data)) return nil } // Test endpoints: // curl http://localhost:8080/api/hello // curl http://localhost:8080/api/users ``` -------------------------------- ### Run Built Container Locally Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md Start the container built with `pack` to serve your function locally. Access the function via `curl` on the specified port. ```sh docker run --rm -p 8080:8080 my-first-function # Output: Serving function... ``` ```sh curl localhost:8080 # Output: Hello, World! ``` -------------------------------- ### Handle Pub/Sub Background Events with CloudEvents (Go) Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Process Google Cloud Pub/Sub messages using background event functions. The framework automatically converts legacy Pub/Sub push formats and CloudEvents. This example uses the `functions.CloudEvent` registration. ```go package function import ( "context" "encoding/base64" "fmt" "log" "cloud.google.com/go/functions/metadata" "github.com/GoogleCloudPlatform/functions-framework-go/functions" ) func init() { functions.CloudEvent("ProcessPubSub", processPubSubCloudEvent) } // PubSubMessage is the payload of a Pub/Sub event type PubSubMessage struct { Message struct { Data string `json:"data"` Attributes map[string]string `json:"attributes"` MessageID string `json:"messageId"` PublishTime string `json:"publishTime"` } `json:"message"` Subscription string `json:"subscription"` } // Alternative: Use legacy background event handler type LegacyPubSubMessage struct { Data []byte `json:"data"` Attributes map[string]string `json:"attributes"` } func handlePubSubBackground(ctx context.Context, msg LegacyPubSubMessage) error { // Access event metadata meta, err := metadata.FromContext(ctx) if err != nil { return fmt.Errorf("metadata.FromContext: %v", err) } log.Printf("Event ID: %s", meta.EventID) log.Printf("Event Type: %s", meta.EventType) log.Printf("Resource: %s", meta.Resource.Name) // Decode base64 message data decodedData, err := base64.StdEncoding.DecodeString(string(msg.Data)) if err != nil { return fmt.Errorf("base64.DecodeString: %v", err) } log.Printf("Message: %s", string(decodedData)) log.Printf("Attributes: %v", msg.Attributes) return nil } // Test with Pub/Sub push format: // curl -X POST http://localhost:8080 \ // -H "Content-Type: application/json" \ // -d '{ // "context": { // "eventId": "1234567890", // "timestamp": "2024-01-15T12:00:00.000Z", // "eventType": "google.pubsub.topic.publish", // "resource": { // "service": "pubsub.googleapis.com", // "name": "projects/my-project/topics/my-topic" // } // }, // "data": { // "data": "SGVsbG8gV29ybGQh", // "attributes": {"key": "value"} // } // }' ``` -------------------------------- ### Curl Request to Local Function Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md This command sends an HTTP GET request to the locally running function at the default port 8080. ```Shell curl localhost:8080 ``` -------------------------------- ### Structured Logging with Execution IDs in Go Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Use `LogWriter` to emit structured logs with execution IDs for request tracing in Google Cloud environments. Execution IDs are auto-generated or can be provided via the `Function-Execution-Id` header. This example demonstrates how to access trace and execution IDs from the request context. ```go package function import ( "fmt" "log" "net/http" "github.com/GoogleCloudPlatform/functions-framework-go/funcframework" "github.com/GoogleCloudPlatform/functions-framework-go/functions" ) func init() { functions.HTTP("TracedFunction", tracedFunction) } func tracedFunction(w http.ResponseWriter, r *http.Request) { // Create a logger that includes execution ID in structured logs l := log.New(funcframework.LogWriter(r.Context()), "", 0) // Get trace and execution IDs from context traceID := funcframework.TraceIDFromContext(r.Context()) execID := funcframework.ExecutionIDFromContext(r.Context()) spanID := funcframework.SpanIDFromContext(r.Context()) l.Printf("Starting request processing") l.Printf("Trace ID: %s, Execution ID: %s, Span ID: %s", traceID, execID, spanID) // Process request... l.Printf("Request completed successfully") fmt.Fprintf(w, "Processed with execution ID: %s", execID) } // Test with custom execution ID: // curl -H "Function-Execution-Id: my-custom-id-123" http://localhost:8080 // Output: Processed with execution ID: my-custom-id-123 // // Log output (JSON structured): // {"message":"Starting request processing","logging.googleapis.com/labels":{"execution_id":"my-custom-id-123"}} ``` -------------------------------- ### Handle HTTP Functions in Go Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md Implement native Go HTTP-style functions using the Functions Framework. Register your function using `functions.HTTP` in the `init` function. ```go 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!")) } ``` -------------------------------- ### Basic Hello World Function in Go Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md A simple HTTP function that responds with 'Hello, World!'. It needs to be registered with the Functions Framework using functions.HTTP. ```Go package function import ( "fmt" "net/http" "github.com/GoogleCloudPlatform/functions-framework-go/functions" ) func init() { functions.HTTP("HelloWorld", helloWorld) } // helloWorld writes "Hello, World!" to the HTTP response. func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, World!") } ``` -------------------------------- ### Build Container with Cloud Build (Bash) Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Build a deployable container image for your Go function using Google Cloud Buildpacks. This command specifies the builder, environment variables for function targeting, and the output image name. ```bash # Build container with Cloud Build pack build \ --builder gcr.io/buildpacks/builder:v1 \ --env GOOGLE_FUNCTION_SIGNATURE_TYPE=http \ --env GOOGLE_FUNCTION_TARGET=HelloWorld \ my-function # Run locally with Docker docker run --rm -p 8080:8080 my-function ``` -------------------------------- ### Run Conformance Tests Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/CONTRIBUTING.md Execute the Functions Framework conformance tests. This ensures compatibility and adherence to standards. ```commandline ./run_conformance_tests.sh ``` -------------------------------- ### Run All Unit Tests Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/CONTRIBUTING.md Execute all unit tests for the project. Ensure all tests pass before submitting changes. ```commandline go test -v ./... ``` -------------------------------- ### Build CloudEvent Function with Pack Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Build a container image for a CloudEvent function using Google Cloud buildpacks. Specify the builder, CloudEvent signature type, and target entry point. ```bash pack build \ --builder gcr.io/buildpacks/builder:v1 \ --env GOOGLE_FUNCTION_SIGNATURE_TYPE=cloudevent \ --env GOOGLE_FUNCTION_TARGET=ProcessCloudEvent \ my-cloudevent-function ``` -------------------------------- ### Register HTTP Functions in Go Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Register standard HTTP handler functions using `functions.HTTP`. The function receives `http.ResponseWriter` and `*http.Request`. Use this for basic web request handling. ```go package function import ( "encoding/json" "fmt" "net/http" "github.com/GoogleCloudPlatform/functions-framework-go/functions" ) func init() { functions.HTTP("HelloWorld", helloWorld) functions.HTTP("GetUser", getUser) } // helloWorld handles basic HTTP requests func helloWorld(w http.ResponseWriter, r *http.Request) { name := r.URL.Query().Get("name") if name == "" { name = "World" } fmt.Fprintf(w, "Hello, %s!", name) } // getUser returns JSON response with user data func getUser(w http.ResponseWriter, r *http.Request) { user := map[string]interface{}{ "id": "12345", "name": "John Doe", "email": "john@example.com", } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(user) } // Test with: // curl http://localhost:8080?name=Developer // Output: Hello, Developer! ``` -------------------------------- ### Run Individual Unit Test Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/CONTRIBUTING.md Run a specific unit test by providing its name. Useful for debugging or focusing on a particular test case. ```commandline go test -v -run TestSplitResource/firebaseauth.googleapis.com ./... ``` -------------------------------- ### Deploy HTTP Function to Cloud Functions (2nd gen) Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Deploy an HTTP-triggered function to Google Cloud Functions (2nd gen). This command sets the runtime, entry point, and source directory. ```bash gcloud functions deploy hello-world \ --gen2 \ --runtime go121 \ --trigger-http \ --entry-point HelloWorld \ --source . ``` -------------------------------- ### Deploy Function to Google Cloud Run Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Deploy a containerized function to Google Cloud Run. This command specifies the image, managed platform, region, and allows unauthenticated access. ```bash gcloud run deploy my-function \ --image gcr.io/my-project/my-function \ --platform managed \ --region us-central1 \ --allow-unauthenticated ``` -------------------------------- ### Define a Background Event Function in Go Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md Implement background event functions by defining a struct for event data and accepting a Go context and the data struct. Ensure the struct matches the expected event payload. ```Go func BackgroundEventFunction(ctx context.Context, data userDefinedEventStruct) error { // Do something with ctx and data. } ``` -------------------------------- ### Access Event Metadata in Go Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md Retrieve event metadata from the Go context using the `cloud.google.com/go/functions/metadata` package. This provides access to additional event information. ```Go m := metadata.FromContext(ctx) ``` -------------------------------- ### Register CloudEvent Functions in Go Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Register functions to handle CloudEvents using `functions.CloudEvent`. The framework automatically unmarshals incoming CloudEvent payloads. This is suitable for event-driven architectures. ```go package function import ( "context" "fmt" "log" cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/GoogleCloudPlatform/functions-framework-go/functions" ) func init() { functions.CloudEvent("ProcessCloudEvent", processCloudEvent) } // StorageObjectData represents a Google Cloud Storage object type StorageObjectData struct { Bucket string `json:"bucket"` Name string `json:"name"` ContentType string `json:"contentType"` Size string `json:"size"` TimeCreated string `json:"timeCreated"` Updated string `json:"updated"` } func processCloudEvent(ctx context.Context, e cloudevents.Event) error { log.Printf("Event Type: %s", e.Type()) log.Printf("Event Source: %s", e.Source()) log.Printf("Event ID: %s", e.ID()) // Parse storage object data var data StorageObjectData if err := e.DataAs(&data); err != nil { return fmt.Errorf("failed to parse event data: %v", err) } log.Printf("Processing file: gs://%s/%s", data.Bucket, data.Name) log.Printf("Content-Type: %s, Size: %s", data.ContentType, data.Size) // Process the file... return nil } // Test with CloudEvent HTTP request: // curl -X POST http://localhost:8080 \ // -H "Content-Type: application/cloudevents+json" \ // -d '{ // "specversion": "1.0", // "type": "google.cloud.storage.object.v1.finalized", // "source": "//storage.googleapis.com/projects/_/buckets/my-bucket", // "id": "1234567890", // "data": { // "bucket": "my-bucket", // "name": "my-file.txt", // "contentType": "text/plain", // "size": "1024" // } // }' ``` -------------------------------- ### Handle CloudEvent Functions in Go Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md Support unmarshalling CloudEvent payloads into `cloudevents.Event` objects for your Go functions. These events are passed as arguments to your function upon receiving a request. Register using `functions.CloudEvent`. ```go package function import ( 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 { // Do something with event.Context and event.Data (via event.DataAs(foo)). return nil } ``` -------------------------------- ### Log Execution ID with LogWriter in Go Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md Leverage the `LogWriter` from the functions-framework-go library (v1.9.0+) to automatically generate and log execution IDs for Cloud Run Functions. If `Function-Exeuction-Id` is not provided, a pseudorandom ID will be generated. ```go package function import ( "fmt" "net/http" "log" "github.com/GoogleCloudPlatform/functions-framework-go/functions" "github.com/GoogleCloudPlatform/functions-framework-go/funcframework" ) func init() { functions.HTTP("HelloWorld", helloWorld) } // helloWorld writes "Hello, World!" to the HTTP response. 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!") } ``` -------------------------------- ### Test HTTP Function Locally Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Use curl to test an HTTP function running locally on port 8080. Ensure the function is running before executing this command. ```bash curl http://localhost:8080 ``` -------------------------------- ### Register Typed Functions in Go Source: https://context7.com/googlecloudplatform/functions-framework-go/llms.txt Register strongly-typed functions that automatically handle JSON marshaling/unmarshaling. The function receives a typed input struct and can return a typed response or error. Ensure your function package is imported to run its init() function. ```go package function import ( "fmt" "strings" "github.com/GoogleCloudPlatform/functions-framework-go/functions" ) func init() { functions.Typed("ProcessOrder", processOrder) functions.Typed("CalculateTotal", calculateTotal) } type OrderRequest struct { OrderID string `json:"orderId"` CustomerID string `json:"customerId"` Items []Item `json:"items"` } type Item struct { ProductID string `json:"productId"` Quantity int `json:"quantity"` Price float64 `json:"price"` } type OrderResponse struct { OrderID string `json:"orderId"` Status string `json:"status"` Total float64 `json:"total"` Message string `json:"message"` } func processOrder(req OrderRequest) (OrderResponse, error) { if req.OrderID == "" { return OrderResponse{}, fmt.Errorf("orderID is required") } var total float64 for _, item := range req.Items { total += item.Price * float64(item.Quantity) } return OrderResponse{ OrderID: req.OrderID, Status: "processed", Total: total, Message: fmt.Sprintf("Order %s processed successfully", req.OrderID), }, nil } type CalculateRequest struct { Values []float64 `json:"values"` } func calculateTotal(req CalculateRequest) (float64, error) { var sum float64 for _, v := range req.Values { sum += v } return sum, nil } // Test with: // curl -X POST http://localhost:8080 \ // -H "Content-Type: application/json" \ // -d '{"orderId":"ORD-123","customerId":"CUST-456","items":[{"productId":"PROD-1","quantity":2,"price":29.99}]}' // Output: {"orderId":"ORD-123","status":"processed","total":59.98,"message":"Order ORD-123 processed successfully"} ``` -------------------------------- ### Provide Custom Execution ID via HTTP Header Source: https://github.com/googlecloudplatform/functions-framework-go/blob/main/README.md Use this method to manually set an execution ID for Cloud Run Functions by including the `Function-Execution-Id` header in your HTTP requests. This is useful for filtering logs per execution. ```sh curl -H "Function-Execution-Id: 123456" localhost:8080 # Output: Hello, World! ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.