我正在 aws lambda 中使用 go 并寻找通用的中间件解决方案。我有以下代码:
func wshandler(ctx context.context, event events.apigatewaywebsocketproxyrequest) (events.apigatewayproxyresponse, error) { } type handlerfunc func(context.context, events.apigatewaywebsocketproxyrequest) (events.apigatewayproxyresponse, error) func logmiddleware(next handlerfunc) handlerfunc { return handlerfunc(func(ctx context.context, event events.apigatewaywebsocketproxyrequest) (events.apigatewayproxyresponse, error) { return next(ctx, event) }) } lambda.start(logmiddleware(wshandler))
中间件函数有一个参数 events.apigatewaywebsocketproxyrequest
因为目标处理程序 wshandler
使用此类型。
我有另一个处理程序,它采用参数 event events.apigatewayproxyrequest
,如下所示。由于参数不匹配,因此无法使用此中间件。
graphqlquerymutationhandler(ctx context.context, event events.apigatewayproxyrequest){ ... }
我尝试将中间件句柄更改为 interface{}
,但不起作用。 go 抱怨这种类型。
type HandlerFunc func(context.Context, interface{}) (interface{}, error)
有没有办法让中间件适用于任何处理程序类型?
正确答案
让我分享我能够在我的系统上复制的工作解决方案。首先给大家分享一下我使用的项目布局:
events/ http_event.json sqs_event.json hello-world/ main.go sqs/ main.go middlewares/ middlewares.go
现在,让我们关注代码。
middlewares/middlewares.go
代码如下:
package middlewares import ( "context" "fmt" "github.com/aws/aws-lambda-go/events" ) type record struct { events.apigatewayproxyrequest `json:",omitempty"` events.sqsevent `json:",omitempty"` } type event struct { records []record `json:"records"` } type handlerfunc func(ctx context.context, event event) (string, error) func logmiddleware(ctx context.context, next handlerfunc) handlerfunc { return handlerfunc(func(ctx context.context, event event) (string, error) { fmt.println("log from middleware!") return next(ctx, event) }) }
让我们总结一下基本概念:
- 我们定义
event
结构体,它将成为我们的通用事件。它是record
结构的包装器。 -
record
结构使用结构嵌入来嵌入我们要处理的所有事件(例如event.apigatewayproxyrequest
和sqsevent
)。 - 我们依靠中间件签名中的这一点来尽可能通用。
events/http_event.json
{ "records": [ { "body": "{\"message\": \"hello world\"}", "resource": "/hello", "path": "/hello", "httpmethod": "get", "isbase64encoded": false, "querystringparameters": { "foo": "bar" }, "pathparameters": { "proxy": "/path/to/resource" }, "stagevariables": { "baz": "qux" }, "headers": { "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "accept-encoding": "gzip, deflate, sdch", "accept-language": "en-us,en;q=0.8", "cache-control": "max-age=0", "cloudfront-forwarded-proto": "https", "cloudfront-is-desktop-viewer": "true", "cloudfront-is-mobile-viewer": "false", "cloudfront-is-smarttv-viewer": "false", "cloudfront-is-tablet-viewer": "false", "cloudfront-viewer-country": "us", "host": "1234567890.execute-api.us-east-1.amazonaws.com", "upgrade-insecure-requests": "1", "user-agent": "custom user agent string", "via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (cloudfront)", "x-amz-cf-id": "cdehvqoznx43vyqb9j2-nvch-9z396uhbp027y2jvkcpnlmgjhqlaa==", "x-forwarded-for": "127.0.0.1, 127.0.0.2", "x-forwarded-port": "443", "x-forwarded-proto": "https" }, "requestcontext": { "accountid": "123456789012", "resourceid": "123456", "stage": "prod", "requestid": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", "requesttime": "09/apr/2015:12:34:56 +0000", "requesttimeepoch": 1428582896000, "identity": { "cognitoidentitypoolid": null, "accountid": null, "cognitoidentityid": null, "caller": null, "accesskey": null, "sourceip": "127.0.0.1", "cognitoauthenticationtype": null, "cognitoauthenticationprovider": null, "userarn": null, "useragent": "custom user agent string", "user": null }, "path": "/prod/hello", "resourcepath": "/hello", "httpmethod": "get", "apiid": "1234567890", "protocol": "http/1.1" } } ] }
这里没什么可说的。
events/sqs_event.json
{ "records": [ { "records": [ { "messageid": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78", "receipthandle": "messagereceipthandle", "body": "my own event payload!", "attributes": { "approximatereceivecount": "1", "senttimestamp": "1523232000000", "senderid": "123456789012", "approximatefirstreceivetimestamp": "1523232000001" }, "messageattributes": {}, "md5ofbody": "4d1d0024b51659ad8c3725f9ba7e2471", "eventsource": "aws:sqs", "eventsourcearn": "arn:aws:sqs:us-east-1:123456789012:myqueue", "awsregion": "us-east-1" } ] } ] }
这同样适用于这里。
hello-world/main.go
package main import ( "context" "fmt" "httplambda/middlewares" "github.com/aws/aws-lambda-go/lambda" ) func lambdahandler(ctx context.context, event middlewares.event) (string, error) { _ = ctx fmt.println("path:", event.records[0].apigatewayproxyrequest.path) fmt.println("hi from http-triggered lambda!") return "", nil } func main() { // start the lambda handler lambda.start(middlewares.logmiddleware(context.background(), lambdahandler)) }
请注意我们如何获取活动信息。
sqs/main.go
package main import ( "context" "fmt" "httplambda/middlewares" "github.com/aws/aws-lambda-go/lambda" ) func lambdaHandler(ctx context.Context, event middlewares.Event) (string, error) { _ = ctx fmt.Println("Queue name:", event.Records[0].SQSEvent.Records[0].EventSourceARN) fmt.Println("Hi from SQS-triggered lambda!") return "", nil } func main() { lambda.Start(middlewares.LogMiddleware(context.Background(), lambdaHandler)) }
决赛
有几个注意事项需要考虑:
- 在遵循此解决方案之前,我尝试使用类型参数,但没有成功。中间件的签名中似乎不允许使用它们。
- 代码过于简化,且尚未做好生产准备。
如果这有帮助或者您需要其他任何东西,请告诉我,谢谢!
以上是如何在 go 中为 lambda 中间件创建泛型类型的详细内容。更多信息请关注PHP中文网其他相关文章!

Interfaceand -polymormormormormormingingoenhancecodereusability and Maintainability.1)DewineInterfaceSattherightabStractractionLevel.2)useInterInterFacesForceFordEffeldIndentientIndoction.3)ProfileCodeTomanagePerformanceImpacts。

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

接口组合在Go编程中通过将功能分解为小型、专注的接口来构建复杂抽象。1)定义Reader、Writer和Closer接口。2)通过组合这些接口创建如File和NetworkStream的复杂类型。3)使用ProcessData函数展示如何处理这些组合接口。这种方法增强了代码的灵活性、可测试性和可重用性,但需注意避免过度碎片化和组合复杂性。

本文讨论了GO中的数组和切片之间的差异,重点是尺寸,内存分配,功能传递和用法方案。阵列是固定尺寸的,分配的堆栈,而切片是动态的,通常是堆积的,并且更灵活。

本文说明了如何在GO中创建和初始化数组,讨论数组和切片之间的差异,并解决了数组的最大尺寸限制。数组与切片:固定与动态,值与参考类型。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。