11.12. 功能开发参考指南

重要

OpenShift Serverless Functions 只是一个技术预览功能。技术预览功能不受红帽产品服务等级协议(SLA)支持,且功能可能并不完整。红帽不推荐在生产环境中使用它们。这些技术预览功能可以使用户提早试用新的功能,并有机会在开发阶段提供反馈意见。

有关红帽技术预览功能支持范围的详情,请参考 https://access.redhat.com/support/offerings/techpreview/

OpenShift Serverless 功能提供模板,可用于创建基本功能。模板启动功能项目 boilerplate,并准备好将其用于 kn func 工具。每个功能模板是为特定的运行时量身定制的,并遵循其约定。使用模板,您可以自动启动功能项目。

可用的运行时模板如下:

11.12.1. Node.js 上下文对象引用

上下文 对象具有多个属性,可供函数开发人员访问。访问这些属性可提供有关 HTTP 请求的信息,并将输出写入集群日志。

11.12.1.1. log

提供一个日志记录对象,可用于将输出写入集群日志。日志遵循 Pino 日志记录 API

日志示例

function handle(context) {
  context.log.info(“Processing customer”);
}

您可以使用 kn func invoke 命令访问功能:

示例命令

$ kn func invoke --target 'http://example.function.com'

输出示例

{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"Processing customer"}

您可以将日志级别更改为 fatalerrorwarninfodebugtracesilent 之一。为此,请使用 config 命令将其中的一个值分配给环境变量 FUNC_LOG_LEVEL,以更改 logLevel 的值。

11.12.1.2. query

返回请求的查询字符串(如果有),作为键值对。这些属性也可在上下文对象本身中找到。

查询示例

function handle(context) {
  // Log the 'name' query parameter
  context.log.info(context.query.name);
  // Query parameters are also attached to the context
  context.log.info(context.name);
}

您可以使用 kn func invoke 命令访问功能:

示例命令

$ kn func invoke --target 'http://example.com?name=tiger'

输出示例

{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"tiger"}

11.12.1.3. 正文(body)

如果有,返回请求正文。如果请求正文包含 JSON 代码,这将会进行解析,以便属性可以直接可用。

body 示例

function handle(context) {
  // log the incoming request body's 'hello' parameter
  context.log.info(context.body.hello);
}

您可以使用 curl 命令调用该函数:

示例命令

$ kn func invoke -d '{"Hello": "world"}'

输出示例

{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"world"}

11.12.1.4. 标头

将 HTTP 请求标头返回为对象。

标头示例

function handle(context) {
  context.log.info(context.headers["custom-header"]);
}

您可以使用 kn func invoke 命令访问功能:

示例命令

$ kn func invoke --target 'http://example.function.com'

输出示例

{"level":30,"time":1604511655265,"pid":3430203,"hostname":"localhost.localdomain","reqId":1,"msg":"some-value"}

11.12.1.5. HTTP 请求

方法
以字符串形式返回 HTTP 请求方法。
httpVersion
以字符串形式返回 HTTP 版本。
httpVersionMajor
将 HTTP 主版本号返回为字符串。
httpVersionMinor
以字符串形式返回 HTTP 次要版本号。