本文介绍Custom Container中事件请求处理程序的结构特点、使用示例和常见问题。
背景介绍
在Custom Container中,函数计算会将Common Headers、Body、POST方法以及/invoke、/initialize路径转发给容器中的HTTP Server。您可以选择实现类似官方支持的Runtime(例如Golang Runtime)的context
和event
函数签名。您也可以直接使用入参请求头(Headers)和请求体 (Body)来编写函数的业务逻辑。更多信息,请参见Custom Runtime事件函数调用。
函数调用说明
当函数是事件请求处理程序时,Http Server仅需实现Path为/invoke
和Method为POST
的对应逻辑即可。
Path | 输入请求 | 预期响应 |
---|---|---|
POST /invoke |
|
响应体:函数Handler的返回值,包括响应码和响应头。
通过Headers中的
x-fc-status 响应,向函数计算汇报本地函数是否执行成功。
说明 在返回的HTTP响应中,建议您同时设置
StatusCode 和x-fc-status 。
|
代码示例
在以下Node.js Express示例中,POST方法和/initialize路径会在函数实例初始化时被函数计算调用,POST方法和/invoke路径为函数计算被调用时的Handler,通过req.headers
以及req.body
获取context
和event
并将函数返回结果通过HTTP Response结构体输出。
'use strict';
const express = require('express');
// Constants
const PORT = 9000;
const HOST = '0.0.0.0';
const app = express();
// Parse request body as JSON
app.use(express.json())
// initialize example, need config Initializer in function meta
app.post('/initialize', (req, res) => {
console.log(req.body)
res.send('Hello FunctionCompute, /initialize\n');
});
// Event function invocation
app.post('/invoke', (req, res) => {
console.log(req.body)
res.send('Hello FunctionCompute, event function\n');
});
var server = app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
server.timeout = 0; // never timeout
server.keepAliveTimeout = 0; // keepalive, never timeout
多语言使用示例
Python
C++
Node.js