Thanks to visit codestin.com
Credit goes to docs.cloudbase.net

Skip to main content

HTTP Function

HTTP Function is a new type of cloud function runtime environment provided by CloudBase, specifically optimized for Web service scenarios. Compared with Custom Functions, HTTP Function supports the standard HTTP request-response model, enabling users to quickly port existing Web services to Serverless architecture.

Prerequisites

  • Have activated Cloud Development Service
  • You have created a Cloud Development environment
  • CloudBase CLI has been installed locally CloudBase CLI

Operation Mechanism

Comparison of Operation Mechanisms between Custom Function and HTTP Function:

FeatureCustom FunctionHTTP Function
Trigger MethodEvent-drivenHTTP Request
Execution EnvironmentNew environment per invocationEnvironment reuse
Connection MethodShort-lived ConnectionsLong-lived Connections supported
Port ListeningNot requiredPort 9000 listening
Use CasesEvent processing, scheduled tasksWeb services, API interfaces

Core Features

HTTP Function has the following core capabilities:

  • HTTP Request Processing: Directly receives and processes standard HTTP requests
  • SSE Support: Supports real-time push with Server-Sent Events
  • WebSocket Support: Supports WebSocket long-lived connection communication
  • File Upload and Download: Supports file upload and download operations
  • Framework Compatibility: Compatible with mainstream Web frameworks such as Express.js and Koa.js

Applicable Scenarios

HTTP Function is particularly suitable for the following scenarios:

  • RESTful API Service: Builds standard REST API interfaces
  • Web Application Migration: Migrate existing Web applications to a Serverless architecture
  • Microservices Architecture: Decomposing monolithic applications into multiple independent microservices
  • Real-time Communication: Real-time data push based on SSE or WebSocket
  • File Processing Service: Provides features such as file uploading, downloading, and conversion

Development Approach

HTTP Function supports two development approaches:

1. Framework Mode

Use the @cloudbase/functions-framework to maintain a functional programming style:

// Use functional style.
exports.main = async function(event, context) {
//Business logic.
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello World' })
};
};

2. Native Mode

Write complete HTTP service code to listen on port 9000:

// Use the Express.js framework
const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.json({ message: 'Hello World' });
});

app.listen(9000, () => {
console.log('Server running on port 9000');
});

Development with Functions Framework

Recommend using the @cloudbase/functions-framework framework for development, as it provides a more concise functional programming experience.

Project Structure

my-web-function/
├── scf_bootstrap # Startup script (required)
├── package.json # Project configuration
└── index.js # Function code

Startup Script

Create the scf_bootstrap file:

#!/bin/bash
node node_modules/@cloudbase/functions-framework/bin/tcb-ff.js --port=9000 --logDirname=/tmp/logs --interceptOutput=false --extendedContextKey=X-Cloudbase-Context
Note

The scf_bootstrap file needs to have executable permissions. In Linux/macOS systems, use the chmod +x scf_bootstrap command to set permissions.

Dependency Configuration

package.json file:

{
"name": "my-web-function",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"@cloudbase/functions-framework": "^1.14.0"
}
}

Basic Example

index.js file:

exports.main = async function(event, context) {
const { method, path, headers, body } = event;

// Handle different HTTP methods
switch (method) {
case 'GET':
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: 'Hello from Web Function',
path,
timestamp: new Date().toISOString()
})
};

case 'POST':
return {
statusCode: 201,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: 'Data received',
data: JSON.parse(body || '{}')
})
};

default:
return {
statusCode: 405,
body: JSON.stringify({ error: 'Method not allowed' })
};
}
};

SSE Real-time Push Example

HTTP functions support Server-Sent Events, enabling real-time data push:

exports.main = async function(event, context) {
// Switch to SSE mode
const sse = context.sse();

// Listen for connection close event
sse.on('close', () => {
console.log('SSE connection closed');
});

// Send real-time data
if (!sse.closed) {
// Send text data
sse.send({ data: 'Hello from SSE function' });

// Send JSON data
sse.send({
data: JSON.stringify({
type: 'notification',
message: 'New message received',
timestamp: Date.now()
})
});

// Send Buffer data
sse.send({ data: Buffer.from('Binary data message') });
}

return '';
};

Function Invocation

HTTP API Invocation

After the HTTP Function is successfully deployed, it can be invoked via the HTTP API:

curl -L 'https://{envId}.api.tcloudbasegateway.com/v1/functions/{functionName}?webfn=true' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer <ACCESS_TOKEN>' \
-d '{}'
Important Note

When invoking a HTTP Function, you must add the webfn=true parameter to the URL; otherwise, the invocation will fail.

Obtain Access Token

Invoking a HTTP Function requires carrying an access token. Refer to Access Token for how to obtain it.

Best Practices

1. Error Handling

exports.main = async function(event, context) {
try {
//Business logic.
const result = await processRequest(event);

return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(result)
};
} catch (error) {
console.error('Function error:', error);

return {
statusCode: 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
error: 'Internal server error',
message: error.message
})
};
}
};

2. Parameter Validation

function validateRequest(event) {
const { method, body } = event;

if (method === 'POST') {
const data = JSON.parse(body || '{}');

if (!data.name || !data.email) {
throw new Error('Missing required fields: name, email');
}

// Email format validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(data.email)) {
throw new Error('Invalid email format');
}
}
}

3. Environment Variable Usage

exports.main = async function(event, context) {
const config = {
apiKey: process.env.API_KEY,
dbUrl: process.env.DATABASE_URL,
debug: process.env.NODE_ENV === 'development'
};

if (!config.apiKey) {
return {
statusCode: 500,
body: JSON.stringify({ error: 'Missing API key configuration' })
};
}

// Business processing using configuration
};

Notes

Important Note
  • HTTP functions must listen on port 9000
  • When using the Functions Framework, you must include the scf_bootstrap startup script
  • The function code package size is limited to 50MB (after compression)
  • The maximum timeout duration for a single request is 900 seconds
  • Supported runtimes: Node.js 12.16, 14.18, 16.13, 18.15

Differences from Event Functions

The event and context parameters of HTTP Functions differ from those of Custom Functions:

  • event object: Contains complete information of the HTTP request (method, path, headers, body, etc.)
  • context object: Provides Web-specific features such as SSE support
  • Environment Variables: Runtime environment variables may vary

Frequently Asked Questions

How to handle file uploads?

exports.main = async function(event, context) {
const { method, headers, body } = event;

if (method === 'POST' && headers['content-type']?.includes('multipart/form-data')) {
// Handle file upload logic
// Note: multipart data needs to be parsed.
return {
statusCode: 200,
body: JSON.stringify({ message: 'File uploaded successfully' })
};
}

return {
statusCode: 400,
body: JSON.stringify({ error: 'Invalid request' })
};
};

How to implement cross-origin support?

exports.main = async function(event, context) {
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
};

// Handle preflight requests
if (event.method === 'OPTIONS') {
return {
statusCode: 200,
headers: corsHeaders,
body: ''
};
}

// Handle normal requests
return {
statusCode: 200,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'Success' })
};
};