示例自定义小组件 - Amazon CloudWatch
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

示例自定义小组件

Amazon 在 JavaScript 和 Python 中提供了示例自定义小组件。您可以使用此列表中各个小组件的链接来创建这些示例小组件。您也可以使用 CloudWatch 控制台创建和自定义小组件。此列表中的链接会打开 Amazon CloudFormation 控制台并使用 Amazon CloudFormation 快速创建链接来创建自定义小组件。

您还可以在 GitHub 上访问自定义小组件示例。

在此列表之后,显示了每种语言的 Echo 小组件的完整示例。

JavaScript
JavaScript 中的示例自定义小组件
Python
Python 中的示例自定义小组件

JavaScript 中的 Echo 小组件

以下是 JavaScript 中的 Echo 示例小组件。

const DOCS = ` ## Echo A basic echo script. Anything passed in the \`\`\`echo\`\`\` parameter is returned as the content of the custom widget. ### Widget parameters Param | Description ---|--- **echo** | The content to echo back ### Example parameters \`\`\` yaml echo: <h1>Hello world</h1> \`\`\` `; exports.handler = async (event) => { if (event.describe) { return DOCS; } let widgetContext = JSON.stringify(event.widgetContext, null, 4); widgetContext = widgetContext.replace(/</g, '&lt;'); widgetContext = widgetContext.replace(/>/g, '&gt;'); return `${event.echo || ''}<pre>${widgetContext}</pre>`; };

Python 中的 Echo 小组件

以下是 Python 中的 Echo 示例小组件。

import json DOCS = """ ## Echo A basic echo script. Anything passed in the ```echo``` parameter is returned as the content of the custom widget. ### Widget parameters Param | Description ---|--- **echo** | The content to echo back ### Example parameters ``` yaml echo: <h1>Hello world</h1> ```""" def lambda_handler(event, context): if 'describe' in event: return DOCS echo = event.get('echo', '') widgetContext = event.get('widgetContext') widgetContext = json.dumps(widgetContext, indent=4) widgetContext = widgetContext.replace('<', '&lt;') widgetContext = widgetContext.replace('>', '&gt;') return f'{echo}<pre>{widgetContext}</pre>'

Java 中的 Echo 小组件

以下是 Java 中的 Echo 示例小组件。

package example; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Handler implements RequestHandler<Event, String>{ static String DOCS = "" + "## Echo\n" + "A basic echo script. Anything passed in the ```echo``` parameter is returned as the content of the custom widget.\n" + "### Widget parameters\n" + "Param | Description\n" + "---|---\n" + "**echo** | The content to echo back\n\n" + "### Example parameters\n" + "```yaml\n" + "echo: <h1>Hello world</h1>\n" + "```\n"; Gson gson = new GsonBuilder().setPrettyPrinting().create(); @Override public String handleRequest(Event event, Context context) { if (event.describe) { return DOCS; } return (event.echo != null ? event.echo : "") + "<pre>" + gson.toJson(event.widgetContext) + "</pre>"; } } class Event { public boolean describe; public String echo; public Object widgetContext; public Event() {} public Event(String echo, boolean describe, Object widgetContext) { this.describe = describe; this.echo = echo; this.widgetContext = widgetContext; } }