### Start veFaaS Golang Function Source: https://github.com/volcengine/vefaas-golang-runtime/blob/main/README.md This Go code demonstrates how to start a veFaaS function. It imports necessary packages, defines a handler function that processes incoming HTTP requests, and logs request details. The handler returns a simple JSON response. ```go package main import ( "context" "fmt" "github.com/volcengine/vefaas-golang-runtime/events" "github.com/volcengine/vefaas-golang-runtime/vefaas" "github.com/volcengine/vefaas-golang-runtime/vefaascontext" ) func main() { // Start your vefaas function =D. vefaas.Start(handler) } // Define your handler function. func handler(ctx context.Context, r *events.HTTPRequest) (*events.EventResponse, error) { fmt.Printf("request id: %s", vefaascontext.RequestIdFromContext(ctx)) fmt.Printf("request headers: %v", r.Headers) return &events.EventResponse{ Headers: map[string]string{ "Content-Type": "application/json", }, Body: []byte("Hello veFaaS!"), }, nil } ``` -------------------------------- ### Start veFaaS Runtime with Initializer and Handler (Go) Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt Starts the veFaaS runtime server with both an initializer function for setup and a handler function for processing requests. The initializer runs once before any requests are handled, useful for establishing database connections or loading configurations. The handler then uses these initialized resources to process requests. ```go package main import ( "context" "database/sql" "fmt" "github.com/volcengine/vefaas-golang-runtime/events" "github.com/volcengine/vefaas-golang-runtime/vefaas" _ "github.com/lib/pq" ) var db *sql.DB func main() { vefaas.StartWithInitializer(handleRequest, initialize) } // Initializer runs once before handling any requests func initialize(ctx context.Context) error { var err error db, err = sql.Open("postgres", "postgresql://user:pass@host:5432/dbname") if err != nil { return fmt.Errorf("failed to connect to database: %w", err) } if err = db.Ping(); err != nil { return fmt.Errorf("database ping failed: %w", err) } fmt.Println("Database connection established") return nil } func handleRequest(ctx context.Context, req *events.HTTPRequest) (*events.EventResponse, error) { // Use initialized database connection var count int err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users").Scan(&count) if err != nil { return &events.EventResponse{ StatusCode: 500, Body: []byte(fmt.Sprintf(`{"error": "%s"}`, err.Error())) }, nil } return &events.EventResponse{ StatusCode: 200, Headers: map[string]string{"Content-Type": "application/json"}, Body: []byte(fmt.Sprintf(`{"user_count": %d}`, count)) }, nil } ``` -------------------------------- ### Build Golang Binary on Windows Source: https://github.com/volcengine/vefaas-golang-runtime/blob/main/README.md This set of commands compiles a Golang program for the Linux amd64 environment using the Windows command prompt. It sets the necessary environment variables for the target OS and architecture, then builds the executable named 'main'. ```batch set GOOS=linux set GOARCH=amd64 set CGO_ENABLED=0 go build -o main ``` -------------------------------- ### Build Golang Binary for Linux amd64 Source: https://github.com/volcengine/vefaas-golang-runtime/blob/main/README.md These shell commands compile a Golang program into a Linux executable for the amd64 architecture, suitable for veFaaS deployment. It ensures the binary is named 'main' and then creates a zip archive containing this binary. ```shell # Build your program that's executable for Linux under architecture amd64. GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main # Zip output. zip main.zip main ``` -------------------------------- ### Start veFaaS Runtime with Request Handler (Go) Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt Starts the veFaaS runtime server, providing a handler function to process incoming HTTP requests. This function utilizes the `events.HTTPRequest` type for input and returns an `events.EventResponse`. It demonstrates accessing request headers and query parameters, and returning a JSON response. ```go package main import ( "context" "fmt" "github.com/volcengine/vefaas-golang-runtime/events" "github.com/volcengine/vefaas-golang-runtime/vefaas" "github.com/volcengine/vefaas-golang-runtime/vefaascontext" ) func main() { vefaas.Start(handleRequest) } func handleRequest(ctx context.Context, req *events.HTTPRequest) (*events.EventResponse, error) { requestID := vefaascontext.RequestIdFromContext(ctx) fmt.Printf("Processing request %s from %s\n", requestID, req.RemoteAddr) // Access request data userAgent := req.Headers["User-Agent"] queryParam := req.QueryStringParameters["name"] responseBody := fmt.Sprintf("Hello %s! User-Agent: %s", queryParam, userAgent) return &events.EventResponse{ StatusCode: 200, Headers: map[string]string{ "Content-Type": "application/json", }, Body: []byte(fmt.Sprintf(`{"message": "%s"}`, responseBody)), }, nil } ``` -------------------------------- ### Go HTTP Request Handler Implementation Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt This Go code demonstrates a complete HTTP request handler for the Vefaas runtime. It defines request and response structures, implements routing logic for different HTTP methods and paths (GET, POST), and handles user creation, listing, and retrieval. Dependencies include the 'context', 'encoding/json', 'fmt' packages, and the Vefaas runtime libraries 'events' and 'vefaas'. It processes JSON payloads and returns standard HTTP responses. ```go package main import ( "context" "encoding/json" "fmt" "github.com/volcengine/vefaas-golang-runtime/events" "github.com/volcengine/vefaas-golang-runtime/vefaas" ) type CreateUserRequest struct { Name string `json:"name"` Email string `json:"email"` } type CreateUserResponse struct { ID string `json:"id"` Message string `json:"message"` } func main() { vefaas.Start(handleHTTPRequest) } func handleHTTPRequest(ctx context.Context, req *events.HTTPRequest) (*events.EventResponse, error) { // Route based on HTTP method and path sswitch { case req.HTTPMethod == "GET" && req.Path == "/users": return listUsers(ctx, req) case req.HTTPMethod == "POST" && req.Path == "/users": return createUser(ctx, req) case req.HTTPMethod == "GET": userID := req.PathParameters["id"] return getUser(ctx, userID) default: return &events.EventResponse{ StatusCode: 404, Body: []byte(`{"error": "not found"}`), }, nil } } func createUser(ctx context.Context, req *events.HTTPRequest) (*events.EventResponse, error) { var userReq CreateUserRequest if err := json.Unmarshal(req.Body, &userReq); err != nil { return &events.EventResponse{ StatusCode: 400, Body: []byte(fmt.Sprintf(`{"error": "invalid JSON: %s"}`, err.Error())), }, nil } // Validate input if userReq.Name == "" || userReq.Email == "" { return &events.EventResponse{ StatusCode: 400, Body: []byte(`{"error": "name and email are required"}`), }, nil } // Create user (mock) response := CreateUserResponse{ ID: "user-12345", Message: fmt.Sprintf("User %s created successfully", userReq.Name), } responseBody, _ := json.Marshal(response) return &events.EventResponse{ StatusCode: 201, Headers: map[string]string{ "Content-Type": "application/json", "Location": "/users/user-12345", }, Body: responseBody, }, nil } func listUsers(ctx context.Context, req *events.HTTPRequest) (*events.EventResponse, error) { // Parse query parameters limit := req.QueryStringParameters["limit"] if limit == "" { limit = "10" } users := []map[string]string{ {"id": "user-1", "name": "Alice"}, {"id": "user-2", "name": "Bob"}, } responseBody, _ := json.Marshal(map[string]interface{}{ "users": users, "limit": limit, }) return &events.EventResponse{ StatusCode: 200, Headers: map[string]string{"Content-Type": "application/json"}, Body: responseBody, }, nil } func getUser(ctx context.Context, userID string) (*events.EventResponse, error) { return &events.EventResponse{ StatusCode: 200, Headers: map[string]string{"Content-Type": "application/json"}, Body: []byte(fmt.Sprintf(`{"id": "%s", "name": "User %s"}`, userID, userID)), }, nil } ``` -------------------------------- ### List Users API Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt Retrieves a list of users via HTTP GET requests. Supports an optional 'limit' query parameter to control the number of users returned. ```APIDOC ## GET /users ### Description Retrieves a list of users via HTTP GET requests. Supports an optional 'limit' query parameter to control the number of users returned. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **limit** (string) - Optional - The maximum number of users to return. Defaults to "10". ### Response #### Success Response (200) - **users** (array) - A list of user objects, each containing 'id' and 'name'. - **limit** (string) - The limit applied to the returned user list. #### Response Example ```json { "users": [ {"id": "user-1", "name": "Alice"}, {"id": "user-2", "name": "Bob"} ], "limit": "10" } ``` ``` -------------------------------- ### Get User API Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt Retrieves details for a specific user via HTTP GET request, using the user's ID in the path. ```APIDOC ## GET /users/{id} ### Description Retrieves details for a specific user via HTTP GET request, using the user's ID in the path. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the user. - **name** (string) - The name of the user. #### Response Example ```json { "id": "user-123", "name": "User 123" } ``` ``` -------------------------------- ### Build and Package Go Function for Vefaas (Linux/macOS) Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt This shell script compiles a Go function for the Linux AMD64 environment, disabling CGO for static linking, and then packages the resulting binary into a zip file suitable for Vefaas deployment. It includes steps for downloading dependencies and optionally including other files in the zip archive. ```bash # For Linux/macOS developers GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main main.go zip main.zip main # For Windows developers (PowerShell) $env:GOOS="linux" $env:GOARCH="amd64" $env:CGO_ENABLED="0" go build -o main main.go # Then use ZIP tool to package the binary # Include additional files if needed zip main.zip main config.yaml static/ # Build with dependencies go mod download GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main zip main.zip main ``` -------------------------------- ### User Creation API Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt Handles the creation of new users via HTTP POST requests. It expects a JSON payload with user details and returns a unique user ID upon successful creation. ```APIDOC ## POST /users ### Description Handles the creation of new users via HTTP POST requests. It expects a JSON payload with user details and returns a unique user ID upon successful creation. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier of the newly created user. - **message** (string) - A confirmation message indicating successful user creation. #### Response Example ```json { "id": "user-12345", "message": "User John Doe created successfully" } ``` #### Error Response (400) - **error** (string) - Describes the error, e.g., "invalid JSON: ..." or "name and email are required". #### Error Response Example ```json { "error": "name and email are required" } ``` ``` -------------------------------- ### Vefaas Go Module Configuration (go.mod) Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt This go.mod file defines the module path for a Vefaas function and specifies the Go version and required runtime dependencies. It ensures that the vefaas-golang-runtime library is correctly vendored and available for the project. ```go module example.com/my-vefaas-function go 1.16 require github.com/volcengine/vefaas-golang-runtime v1.0.0 ``` -------------------------------- ### Go Error Handling and Response Formatting in veFaaS Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt This Go code demonstrates comprehensive error handling for veFaaS functions. It includes input validation, JSON parsing error management, business logic error propagation, and custom error response generation. The function `handleWithErrors` is the main entry point, and `errorResponse` utility helps create standardized error responses. ```go package main import ( "context" "encoding/json" "fmt" "log" "github.com/volcengine/vefaas-golang-runtime/events" "github.com/volcengine/vefaas-golang-runtime/vefaas" "github.com/volcengine/vefaas-golang-runtime/vefaascontext" ) type ErrorResponse struct { Error string `json:"error"` RequestID string `json:"request_id,omitempty"` Code string `json:"code,omitempty"` } func main() { vefaas.Start(handleWithErrors) } func handleWithErrors(ctx context.Context, req *events.HTTPRequest) (*events.EventResponse, error) { requestID := vefaascontext.RequestIdFromContext(ctx) // Validate input if req.HTTPMethod != "POST" { return errorResponse(405, "METHOD_NOT_ALLOWED", "Only POST is allowed", requestID), nil } // Parse JSON body var data map[string]interface{} if err := json.Unmarshal(req.Body, &data); err != nil { log.Printf("Request %s: JSON parse error: %v", requestID, err) return errorResponse(400, "INVALID_JSON", err.Error(), requestID), nil } // Business logic with error handling result, err := processData(ctx, data) if err != nil { log.Printf("Request %s: Processing error: %v", requestID, err) // Return function error (runtime will handle it) return nil, fmt.Errorf("failed to process data: %w", err) } // Success response responseBody, _ := json.Marshal(map[string]interface{}{ "status": "success", "result": result, "request_id": requestID, }) return &events.EventResponse{ StatusCode: 200, Headers: map[string]string{"Content-Type": "application/json"}, Body: responseBody, }, nil } func errorResponse(statusCode int, code, message, requestID string) *events.EventResponse { errResp := ErrorResponse{ Error: message, RequestID: requestID, Code: code, } body, _ := json.Marshal(errResp) return &events.EventResponse{ StatusCode: statusCode, Headers: map[string]string{"Content-Type": "application/json"}, Body: body, } } func processData(ctx context.Context, data map[string]interface{}) (string, error) { // Simulate processing if data["id"] == nil { return "", fmt.Errorf("missing required field: id") } return "processed", nil } ``` -------------------------------- ### Process CloudEvents with Go Runtime Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt This Go code defines a CloudEvent handler for the Vefaas runtime. It uses the 'events' and 'vefaas' packages to process different event types such as timers, TOS, Kafka, SNS, and TLS. The handler parses event data based on the event type and performs corresponding actions, returning an EventResponse. It requires the 'github.com/volcengine/vefaas-golang-runtime/events' and 'github.com/volcengine/vefaas-golang-runtime/vefaas' packages. ```go package main import ( "context" "encoding/json" "fmt" "github.com/volcengine/vefaas-golang-runtime/events" "github.com/volcengine/vefaas-golang-runtime/vefaas" ) type TimerEventData struct { TriggerTime string `json:"triggerTime"` Message string `json:"message"` } type TOSEventData struct { Bucket string `json:"bucket"` Key string `json:"key"` Size int64 `json:"size"` } func main() { vefaas.Start(handleCloudEvent) } func handleCloudEvent(ctx context.Context, event *events.CloudEvent) (*events.EventResponse, error) { fmt.Printf("Received CloudEvent: Type=%s, Source=%s, ID=%s\n", event.Type(), event.Source(), event.ID()) // Route based on event type switch event.Type() { case events.FaasTimerEvent: return handleTimerEvent(ctx, event) case events.FaasTosEvent: return handleTOSEvent(ctx, event) case events.FaasKafkaEvent: return handleKafkaEvent(ctx, event) case events.FaasSnsEvent: return handleSNSEvent(ctx, event) case events.FaasTlsEvent: return handleTLSEvent(ctx, event) default: return &events.EventResponse{ StatusCode: 400, Body: []byte(fmt.Sprintf(`{"error": "unsupported event type: %s"}`, event.Type())), }, nil } } func handleTimerEvent(ctx context.Context, event *events.CloudEvent) (*events.EventResponse, error) { var data TimerEventData if err := event.DataAs(&data); err != nil { return nil, fmt.Errorf("failed to parse timer event data: %w", err) } fmt.Printf("Timer triggered at %s: %s\n", data.TriggerTime, data.Message) // Perform scheduled task result := performScheduledTask() return &events.EventResponse{ StatusCode: 200, Body: []byte(fmt.Sprintf(`{"status": "completed", "result": "%s"}`, result)), }, nil } func handleTOSEvent(ctx context.Context, event *events.CloudEvent) (*events.EventResponse, error) { var data TOSEventData if err := event.DataAs(&data); err != nil { return nil, fmt.Errorf("failed to parse TOS event data: %w", err) } fmt.Printf("Object uploaded: bucket=%s, key=%s, size=%d bytes\n", data.Bucket, data.Key, data.Size) // Process uploaded file if err := processUploadedFile(data.Bucket, data.Key); err != nil { return &events.EventResponse{ StatusCode: 500, Body: []byte(fmt.Sprintf(`{"error": "%s"}`, err.Error())), }, nil } return &events.EventResponse{ StatusCode: 200, Body: []byte(`{"status": "file processed"}`), }, nil } func handleKafkaEvent(ctx context.Context, event *events.CloudEvent) (*events.EventResponse, error) { // Get raw event data dataBytes, err := json.Marshal(event.Data()) if err != nil { return nil, fmt.Errorf("failed to marshal Kafka event data: %w", err) } fmt.Printf("Kafka message received: %s\n", string(dataBytes)) // Process Kafka message processMessage(dataBytes) return &events.EventResponse{ StatusCode: 200, Body: []byte(`{"status": "message processed"}`), }, nil } func handleSNSEvent(ctx context.Context, event *events.CloudEvent) (*events.EventResponse, error) { fmt.Printf("SNS notification received: %v\n", event.Data()) return &events.EventResponse{StatusCode: 200}, nil } func handleTLSEvent(ctx context.Context, event *events.CloudEvent) (*events.EventResponse, error) { fmt.Printf("TLS log event received: %v\n", event.Data()) return &events.EventResponse{StatusCode: 200}, nil } func performScheduledTask() string { return "cleanup completed" } func processUploadedFile(bucket, key string) error { return nil } func processMessage(data []byte) {} ``` -------------------------------- ### Handle HTTP and CloudEvent in Single Go Handler Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt This Go function demonstrates how to handle both HTTP requests and CloudEvents within a single handler using type assertion. It distinguishes between incoming event types and routes them to appropriate internal handlers. Dependencies include the vefaas-golang-runtime package. ```go package main import ( "context" "encoding/json" "fmt" "github.com/volcengine/vefaas-golang-runtime/events" "github.com/volcengine/vefaas-golang-runtime/vefaas" ) func main() { vefaas.Start(handleAnyEvent) } func handleAnyEvent(ctx context.Context, payload interface{}) (*events.EventResponse, error) { // Use type assertion to determine the event type sswitch event := payload.(type) { case *events.HTTPRequest: return handleHTTPInAnyHandler(ctx, event) case *events.CloudEvent: return handleCloudEventInAnyHandler(ctx, event) default: return &events.EventResponse{ StatusCode: 400, Body: []byte(fmt.Sprintf(`{"error": "unknown event type: %T"}`, payload)), }, nil } } func handleHTTPInAnyHandler(ctx context.Context, req *events.HTTPRequest) (*events.EventResponse, error) { fmt.Printf("HTTP request: %s %s\n", req.HTTPMethod, req.Path) response := map[string]interface{}{ "type": "http", "method": req.HTTPMethod, "path": req.Path, "query": req.QueryStringParameters, } body, _ := json.Marshal(response) return &events.EventResponse{ StatusCode: 200, Headers: map[string]string{"Content-Type": "application/json"}, Body: body, }, nil } func handleCloudEventInAnyHandler(ctx context.Context, event *events.CloudEvent) (*events.EventResponse, error) { fmt.Printf("CloudEvent received: %s from %s\n", event.Type(), event.Source()) response := map[string]interface{}{ "type": "cloudevent", "eventType": event.Type(), "eventSource": event.Source(), "eventID": event.ID(), } body, _ := json.Marshal(response) return &events.EventResponse{ StatusCode: 200, Headers: map[string]string{"Content-Type": "application/json"}, Body: body, }, nil } ``` -------------------------------- ### Not Found API Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt Handles requests to undefined endpoints, returning a 404 Not Found error. ```APIDOC ## Default (404 Not Found) ### Description Handles requests to undefined endpoints, returning a 404 Not Found error. ### Method Any ### Endpoint Any (unmatched) ### Response #### Error Response (404) - **error** (string) - Indicates that the requested resource was not found. #### Response Example ```json { "error": "not found" } ``` ``` -------------------------------- ### Access Vefaas Context Metadata in Go Source: https://context7.com/volcengine/vefaas-golang-runtime/llms.txt This Go function demonstrates how to retrieve request metadata such as request ID and IAM credentials (Access Key ID, Secret Access Key, Session Token) from the function's context. It utilizes the vefaascontext package and can use these credentials to interact with AWS services. Dependencies include vefaas-golang-runtime and vefaascontext. ```go package main import ( "context" "fmt" "github.com/volcengine/vefaas-golang-runtime/events" "github.com/volcengine/vefaas-golang-runtime/vefaas" "github.com/volcengine/vefaas-golang-runtime/vefaascontext" ) func main() { vefaas.Start(handleWithContext) } func handleWithContext(ctx context.Context, req *events.HTTPRequest) (*events.EventResponse, error) { // Extract request metadata requestID := vefaascontext.RequestIdFromContext(ctx) accessKeyID := vefaascontext.AccessKeyIdFromContext(ctx) secretAccessKey := vefaascontext.SecretAccessKeyFromContext(ctx) sessionToken := vefaascontext.SessionTokenFromContext(ctx) fmt.Printf("Request ID: %s\n", requestID) fmt.Printf("Access Key ID: %s\n", accessKeyID) // Use IAM credentials for AWS SDK calls if accessKeyID != "" && secretAccessKey != "" { // Initialize AWS SDK with temporary credentials err := callAWSService(accessKeyID, secretAccessKey, sessionToken) if err != nil { return &events.EventResponse{ StatusCode: 500, Body: []byte(fmt.Sprintf(`{"error": "AWS service call failed: %s"}`, err.Error())) }, nil } } // Include request ID in response for tracing response := fmt.Sprintf(`{ "request_id": "%s", "status": "success", "message": "Credentials retrieved and used" }`, requestID) return &events.EventResponse{ StatusCode: 200, Headers: map[string]string{ "Content-Type": "application/json", "X-Request-ID": requestID, }, Body: []byte(response), }, nil } func callAWSService(accessKeyID, secretAccessKey, sessionToken string) error { // Use credentials with AWS SDK // cfg, err := config.LoadDefaultConfig(ctx, // config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider( // accessKeyID, secretAccessKey, sessionToken, // )), // ) return nil } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.