Skip to main content

HTTP Cloud Function

HTTP cloud functions are a new runtime environment provided by TCB, specifically optimized for Web service scenarios. Compared to regular functions, HTTP cloud functions support standard HTTP request-response patterns, allowing users to quickly port existing Web services to a Serverless architecture.

Prerequisites

  • TCB service has been enabled
  • The TCB environment has been created
  • CloudBase CLI has been installed locally

Operation Mechanism

Comparison of Operation Mechanisms between HTTP Cloud Functions and Regular Functions:

FeatureRegular FunctionHTTP Cloud Function
Trigger MethodEvent-DrivenHTTP Request
Execution EnvironmentA new environment is created for each invocationEnvironment reuse is supported
Connection MethodShort ConnectionSupports Long Connection
Port ListeningNo port listening requiredListens on port 9000
Applicable ScenariosEvent Processing, Scheduled TasksWeb Services, API Interfaces

Core Features

HTTP Cloud Function provides the following core capabilities:

  • HTTP Request Handling: Directly receive and process standard HTTP requests.
  • SSE Support: Supports real-time push of Server-Sent Events.
  • WebSocket Support: Supports WebSocket long-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 Cloud Function is particularly well-suited for the following scenarios:

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

Development Approach

HTTP Cloud Function supports two development approaches:

1. Framework Mode

Use the @cloudbase/functions-framework 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 listening 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

We recommend using the @cloudbase/functions-framework framework for development, which 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 must have executable permissions. On Linux/macOS systems, use the chmod +x scf_bootstrap command to set the 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 cloud 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 events
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 '';
};

Deployment Configuration

Deploy Using CLI

  1. Install Dependencies:
npm install
  1. Create the cloudbaserc.json configuration file:
{
"envId": "your-env-id",
"functions": [
{
"name": "webFunction",
"type": "web",
"source": "./",
"runtime": "Nodejs16.13",
"memorySize": 256,
"timeout": 60,
"environment": {
"NODE_ENV": "production"
}
}
]
}
  1. Deploy function:
cloudbase functions:deploy webFunction

Deploy via TCB

  1. Log in to TCB
  2. Select the target environment and go to the [Cloud Function] page
  3. Click [New Function] and select the [HTTP cloud function] type
  4. Upload the code package or edit the code online
  5. Configure function parameters and deploy

Function Invocation

HTTP API Invocation

After the HTTP cloud function is successfully deployed, it can be invoked via 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 an HTTP cloud function, the webfn=true parameter must be added to the URL; otherwise, the invocation will fail.

Obtain an Access Token

Invoking an HTTP cloud function requires carrying an access token. For how to obtain it, see: Access Token

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' })
};
}

// Use configuration for business processing
};

Notes

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

Differences from Regular Functions

The event and context parameters of HTTP cloud functions differ from those of event functions:

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

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: Requires parsing multipart data
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' })
};
};