"HTTP Cloud Function" is a type of cloud function designed specifically for web service scenarios, offering native HTTP support, real-time communication capabilities, and multi-function routing features.
HTTP Cloud Function Development Guide
Creating the Function Entry File
Node.js Project Example
Create index.js as the HTTP function entry file:
const http = require('http')
const port = 9000
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Hello World!')
})
server.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`)
})
Python Project Example
Create main.py as the HTTP function entry file:
from http.server import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write(b'Hello World!)
if __name__ == '__main__':
server = HTTPServer(('0.0.0.0', 9000), Handler)
print('Server listening at http://localhost:9000')
server.serve_forever()
}
Creating a Bootstrap Script
Create a file named scf_bootstrap (without an extension) in the project root directory, containing the command to launch the project:
Example for Nodejs Project
#!/bin/bash
node index.js
Example for Python Project
#!/bin/bash
python3 main.py
Project Structure
Nodejs Project Example
The complete project directory structure is as follows:
nodejs-http-function/
├── scf_bootstrap # Startup script (required, no extension)
├── package.json # Project configuration file
├── index.js # Main function entry file
└── node_modules/ # Dependency packages (generated after npm install)
Python Project Example
The complete project directory structure is as follows:
python-http-function/
├── scf_bootstrap # Startup script (required, no extension)
└── main.py # Main function entry file
Reference Resources:
- More examples: Example Code Repository
- Template codes: JavaScript Template | TypeScript Template
Function Framework
HTTP Cloud Functions support the use of web-related frameworks for development, such as Express, Koa, NestJS in Node.js environments, Flask and Django in Python environments, as well as web frameworks in other programming languages.
Since HTTP Cloud Functions integrate with web frameworks, request routing can be implemented using these frameworks, aligning better with developers' habitual coding styles.
In addition to implementing business logic with web frameworks, function initialization relies on the startup file scf_bootstrap.
Explanation of scf_bootstrap Bootstrap File
In HTTP Cloud Functions, scf_bootstrap is an essential startup file that serves as the entry point for launching the Web Server. It is responsible for initiating your Web service, configuring the runtime environment, loading dependencies, and ensuring the service is ready to receive requests.
The scf_bootstrap file is executed automatically when the Cloud Function instance starts. Its main responsibilities include:
| Responsibility | Description |
|---|---|
| Launch Web Service | Ensures your Web service starts and listens for requests on port 9000 by default. |
| Environment Configuration | Sets the paths for required libraries and environment variables during runtime. |
| Dependency Loading | Loads custom languages, version-specific libraries, and extensions. If real-time dependency fetching is needed, consider storing them in /tmp. |
| Global Initialization | Performs global operations before function execution, such as initializing the HTTP Client or creating a database connection pool, for reuse during calls. |
| Plugin Loading | Initializes security, monitoring, and other plugins. |
To ensure the startup file runs correctly, the following requirements must be met:
| Requirement | Description |
|---|---|
| Fixed File Name | The file must be named scf_bootstrap; other names are not allowed. |
| Executable Permissions | The file must have execute permissions (recommended: 777 or 755). |
| System Compatibility | Must run on CentOS or standard Linux systems. |
| Shebang Statement | For Shell scripts, the first line must contain #!/bin/bash. |
| Absolute Paths | Use absolute paths for startup commands (refer to “Standard Language Environment Absolute Paths”). |
| Listening Address | It is recommended to use 0.0.0.0 instead of the local loopback address 127.0.0.1. |
| File Format | The file must end with an LF newline (not CRLF). |
| Write Permission Limits | In a standard environment, only /tmp should be writable. Be careful with output file paths. |
⚠️ Tip: On Linux/macOS, use
chmod +x scf_bootstraporchmod 777 scf_bootstrapto grant execute permissions.
Standard Language Environment Absolute Paths
When writing startup commands, use the absolute paths specific to each language. Here are reference paths for common versions:
| Language Version | Absolute Path |
|---|---|
| Node.js 18.15 | /var/lang/node18/bin/node |
| Node.js 16.13 | /var/lang/node16/bin/node |
| Node.js 14.18 | /var/lang/node14/bin/node |
| Node.js 12.16 | /var/lang/node12/bin/node |
| Python 3.10 | /var/lang/python310/bin/python3.10 |
| Python 3.9 | /var/lang/python39/bin/python3.9 |
| Python 3.7 | /var/lang/python37/bin/python3.7 |
| Python 3.6 | /var/lang/python3/bin/python3.6 |
| PHP 8.0 | /var/lang/php80/bin/php |
| PHP 7.4 | /var/lang/php74/bin/php |
| PHP 7.2 | /var/lang/php7/bin/php |
| Java 11 | /var/lang/java11/bin/java |
| Java 8 | /var/lang/java8/bin/java |
Examples of scf_bootstrap
For Express framework:
#!/bin/bash
export PORT=9000
/var/lang/node18/bin/node app.js
For Flask framework:
#!/bin/bash
export PORT=9000
/var/lang/python3/bin/python3 app.py
For Django framework:
#!/bin/bash
export PORT=9000
/var/lang/python3/bin/python3 manage.py runserver 0.0.0.0:9000
For SpringBoot framework:
#!/bin/bash
export PORT=9000
/java -Dserver.port=${PORT} -jar target/my-app.jar
Calling HTTP Cloud Functions
Using the wx.cloud.callHTTPFunction method in the Weixin Mini Program native SDK, you can directly invoke HTTP cloud functions, supporting streaming transmission (SSE).
⚠️ Version Requirement: When calling HTTP cloud functions, ensure that the version of the Mini Program basic library is 3.15.1 or higher.
Calling Method
The wx.cloud.callHTTPFunction method is similar to wx.request in usage, supporting various request methods and streaming transmission.
Basic Usage Example:
wx.cloud.callHTTPFunction({
name: 'my-http-function', // Name of the cloud function
config: {
env: 'your-env-id', // Optional: Specify the cloud development environment ID
},
data: { key: 'value' }, // Request data
path: '/api/hello', // Request path
method: 'post', // Request method
header: {
'X-Custom-Header': 'value', // Custom request header
},
timeout: 1500, // Timeout duration in milliseconds
enableChunked: true, // Enable streaming transmission
onHeadersReceived: (res) => {
console.log("httpFunc headers received", res)
},
onChunkedReceived: (res) => {
console.log("chunked", res);
const arrayBuffer = res.data;
const uint8Array = new Uint8Array(arrayBuffer);
let str = '';
for (let i = 0; i < uint8Array.length; i++) {
str += String.fromCharCode(uint8Array[i]);
}
// Attempt to decode UTF-8
try {
const decodedStr = decodeURIComponent(escape(str));
console.log('SSE chunk received:', decodedStr);
} catch (e) {
console.log('SSE chunk received (raw):', str);
}
},
success: (res) => {
console.log("httpFunc success", res)
},
fail: (err) => {
console.log("callHttpFunction err", err)
},
});
Request Parameter Description
Invocation Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
name |
String | Yes | Name of the cloud function |
config |
Object | No | Configuration object |
config.env |
String | No | Cloud development environment ID |
data |
Object | No | Request data (body) |
path |
String | Yes | Request path |
method |
String | Yes | Request method: get / post / put / delete / head / options |
header |
Object | No | Custom request headers |
enableChunked |
Boolean | No | Whether to enable streaming transmission |
dataType |
String | No | Specifies the response data type, effective only in non-streaming mode |
responseType |
String | No | Specifies the response data type, effective only in non-streaming mode |
timeout |
Number | No | Request timeout in milliseconds; must be set to less than 1500 ms |
success |
Function | No | Callback for successful requests |
fail |
Function | No | Callback for failed requests |
complete |
Function | No | Callback when the request is completed (executed regardless of success or failure) |
onHeadersReceived |
Function | No | Callback when response headers are received in streaming mode |
onChunkedReceived |
Function | No | Callback when chunk data is received in streaming mode |
Return Parameters
| Parameter | Type | Description |
|---|---|---|
data |
string / Object / ArrayBuffer | Returned data; ArrayBuffer when returned in streams |
statusCode |
number | HTTP status code |
header |
Object | Response headers |
Real-time Communication Capabilities
HTTP Cloud Functions offer two real-time communication methods: 「SSE (Server-Sent Events)」and「WebSocket」.
SSE (Server-Sent Events)
"SSE" is a server-push technology based on HTTP that supports unidirectional real-time data stream transmission (server → client).
Features:
- Based on the HTTP protocol with excellent compatibility — works out of the box with no additional configuration
- Clients can automatically reconnect
- Simple to implement with low resource overhead
- Well-suited for scenarios such as AI conversational streaming output, real-time log display, and progress updates
Code Example:
Implementing SSE streaming data transfer using the Express framework::
const express = require('express');
const app = express();
// SSE route setup
app.get('/stream', (req, res) => {
// Set SSE response headers
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
console.log('New SSE connection established');
// Stream data to client
const msg = ['SSE', 'empowers', 'GPT', 'applications', '!', 'Happy', 'chatting', '!'];
let index = 0;
const intervalId = setInterval(() => {
if (index < msg.length) {
// Send SSE message to client
const data = {
id: index,
content: msg[index],
};
res.write(`data: ${JSON.stringify(data)}\n\n`);
index++;
} else {
// All data sent, close connection
clearInterval(intervalId);
res.end();
}
}, 1000);
// Clean up when client disconnects
req.on('close', () => {
_clearInterval(intervalId);
console.log('SSE connection closed');
});
});
// Start server, listening on port 9000
app.listen(9000, () => {
console.log('SSE server started, listening on port 9000');
});
Mini Program client code for receiving SSE data:
wx.cloud.callHTTPFunction({
name: 'express-sse', // Adjust function name as needed
path: '/sse',
method: 'GET',
enableChunked: true,
onHeadersReceived: (res) => {
console.log("Received HTTP function response headers", res)
},
onChunkedReceived: (res) => {
console.log("Received chunked data", res);
const arrayBuffer = res.data;
const uint8Array = new Uint8Array(arrayBuffer);
let str = '';
for (let i = 0; i < uint8Array.length; i++) {
str += String.fromCharCode(uint8Array[i]);
}
// Attempt to decode byte array as UTF-8 string
try {
const decodedStr = decodeURIComponent(escape(str));
console.log('Parsed SSE data:', decodedStr);
} catch (e) {
console.log('Raw SSE byte string:', str);
}
},
});
WebSocket
WebSocket is a full-duplex communication protocol that supports bidirectional real-time communication between the server and the client.
Features:
- Bidirectional real-time communication with persistent connections and low latency
- Requires enabling WebSocket protocol support in the console
- The server must listen on port 9000
- Ideal for real-time chat, collaborative editing, game servers, and other applications
Code Example:
Implementing a WebSocket server using the ws library:
const WebSocket = require('ws');
// Create a WebSocket server that listens on port 9000
const wss = new WebSocket.Server({ port: 9000 });
wss.on('connection', (ws) => {
console.log('New connection established');
// Send a welcome message
ws.send('Welcome to the WebSocket service');
// Receive messages
ws.on('message', (message) => {
console.log('Received message:', message.toString());
// Respond to the message
const response = {
type: 'response',
data: message.toString(),
timestamp: Date.now(),
};
ws.send(JSON.stringify(response));
});
// Handle connection closure
ws.on('close', () => {
console.log('Connection closed');
});
// Handle errors
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
});
console.log('WebSocket server started, listening on port 9000');
Technical Comparison
| Feature | SSE | WebSocket |
|---|---|---|
| Communication Mode | Unidirectional (Server→Client) | Bidirectional (Server↔Client) |
| Protocol | HTTP | WebSocket Protocol |
| Implementation Complexity | Simple | Relatively Complex |
| Configuration Requirements | No configuration required | Requires console activation |
| Automatic Reconnection | Yes | No (manual implementation needed) |
| Applicable Scenarios | Unidirectional data push | Real-time bidirectional communication |
Recommendations:
- If only server-side data push is needed (e.g., AI responses, logs, progress updates) → Choose SSE
- For real-time bidirectional communication (e.g., chats, collaboration, games) → Choose WebSocket