範例自訂小工具 - Amazon CloudWatch

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

範例自訂小工具

AWS 在兩個 JavaScript 和 Python 中提供了示例自定義部件。您可以使用此清單中每個小工具的連結來建立這些範例小工具。或者,您也可以使用 CloudWatch 主控台建立和自訂 Widget。此清單中的連結會開啟 AWS CloudFormation 主控台,並使用 AWS CloudFormation 快速建立連結來建立自訂 Widget。

您也可以在上存取自訂小器具範例GitHub

在此清單之後,將顯示每種語言的 Echo 小工具的完整範例。

JavaScript
在示例自定義部件 JavaScript
Python
Python 中的範例自訂小工具

迴聲小部件 JavaScript

以下是中的 Echo 範例小器具 JavaScript。

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