在 Go 中为 AWS Lambda 指定多个事件处理程序
来源:stackoverflow
时间:2024-05-01 10:00:35 482浏览 收藏
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《在 Go 中为 AWS Lambda 指定多个事件处理程序》,聊聊,我们一起来看看吧!
通常,go 中的 aws lambda 事件处理程序代码(使用无服务器框架)编码为:
package main
import (
"fmt"
"context"
"github.com/aws/aws-lambda-go/lambda"
)
type myevent struct {
name string `json:"name"`
}
func handlerequest(ctx context.context, name myevent) (string, error) {
return fmt.sprintf("hello %s!", name.name ), nil
}
func main() {
lambda.start(handlerequest)
}
serverless.yml 文件包含如下部分:
skeleton-go-get:
name: skeleton-go-get
runtime: go1.x
handler: go-handler # <- this specifies a file, not a function.
events:
- http:
path: skeleton/go
method: get
^ 创建一个请求处理程序...但现在我希望我的一个 go 脚本/程序包含 http get 和 post 请求的事件处理程序,而不是每个无服务器函数使用一个 go 程序文件。
这在 node.js、ruby、python 等语言中是可能的,通过 serverless.yml 指定处理程序文件中的哪个函数将用于哪个无服务器函数。例如(对于 python 函数):
[...]
functions:
skeleton-python-get:
name: skeleton-python-get
handler: python-handler.handle_get # <- specifies the http get handler.
events:
- http:
path: skeleton/python
method: get
skeleton-python-post:
name: skeleton-python-post
handler: python-handler.handle_post # <- specifies the http post handler.
events:
- http:
path: skeleton/python
method: post
我无法让同样的技巧适用于 go。我尝试在 main() 中包含正确的请求,但无济于事:
func handlegetrequest(ctx context.context, name myevent) (string, error) {
return fmt.sprintf("hello %s!", name.name ), nil
}
func handlepostrequest(ctx context.context, name myevent) (string, error) {
return fmt.sprintf("hello %s!", name.name ), nil
}
func main() {
lambda.start(handlegetrequest)
lambda.start(handlepostrequest) // <- attempt to add another handler.
}
在 serverless.yml 文件中为 go 处理程序指定多个事件处理函数也不起作用:该函数不是处理程序声明的有效部分。
skeleton-go-get:
name: skeleton-go-get
runtime: go1.x
handler: go-handler.HandleGet # <- Attempt to specify a function.
events:
- http:
path: skeleton/go
method: get
skeleton-go-post:
name: skeleton-go-post
runtime: go1.x
handler: go-handler.HandlePost # <- Attempt to specify a function.
events:
- http:
path: skeleton/go
method: post
问:如何在一个 go 程序中包含多个 aws lambda 事件处理程序(使用无服务器框架)?
解决方案
您可以对 get 和 post 使用相同的函数(和处理程序):
skeleton-go:
name: skeleton-go
runtime: go1.x
handler: go-handler
events:
- http:
path: skeleton/go
method: get
- http:
path: skeleton/go
method: post
使用go的built-in HTTP router或使用第三方的,例如Gorilla Mux或Chi,如下面的示例代码所示(因为这是我方便的)。本质上,您正在构建一个 go http 服务器,但是是在 lambda 中。因此,请按照设置 go web 服务器的详细信息进行操作,并查看 AWS's API Gateway Proxy。
package main
import (
"context"
"net/http"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/go-chi/chi"
chiproxy "github.com/awslabs/aws-lambda-go-api-proxy/chi"
)
var adapter *chiproxy.chilambda
func getskeleton(w http.responsewriter, r *http.request) {
...
}
func postskeletontomom(w http.responsewriter, r *http.request) {
...
}
func init() {
r := chi.newrouter()
r.get("/skeleton/go", getskeleton)
r.post("/skeleton/go", postskeletontomom)
adapter = chiproxy.new(r)
}
func lambdahandler(ctx context.context, req events.apigatewayproxyrequest) (events.apigatewayproxyresponse, error) {
c, err := adapter.proxywithcontext(ctx, req)
return c, err
}
func main() {
lambda.start(lambdahandler)
}您不需要在 lambda 中自行构建 go 服务器,因为您已经通过无服务器框架为您提供 api 网关...
我使用了 aws cloudformation + sam,并且使用了 http api 网关(不是 rest),但它应该以类似的方式运行...
首先...您需要将其变成 1 个 lambda 函数来处理 2 个事件,如下所示:
skeleton-go-get:
name: skeleton-go-get
runtime: go1.x
handler: go-handler # <- this specifies a file, not a function.
events:
- http:
path: skeleton/go
method: get
- http:
path: skeleton/go
method: post
在你的 lambda 中,你应该有:
package main
import ...
func getSkeleton(event events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
// Return APIGateway Response
}
func postSkeleton(event events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
// Return APIGateway Response
}
func handler(_ context.Context, event events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
// Log Events
eventJson, _ := json.Marshal(event)
log.Printf("EVENT: %s", string(eventJson))
switch event.RouteKey {
case "GET /skeleton/go":
return getSkeleton(event)
case "POST /skeleton/go":
return postSkeleton(event)
default:
return events.APIGatewayV2HTTPResponse{
StatusCode: 400
}, nil
}
}
func main() {
lambda.Start(handler)
}终于介绍完啦!小伙伴们,这篇关于《在 Go 中为 AWS Lambda 指定多个事件处理程序》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
Golang · Go问答 | 2天前 | 并发 · channel · select · 性能排查 · Go问答 · select Go channel context default CPU飙高 忙等循环 ticker438 收藏
-
Golang · Go问答 | 2天前 | pprof · trace · 性能排查 · Go问答 · 服务安全 · Go pprof 生产环境 trace 安全入口 net/http/pprof 性能排障349 收藏
-
Golang · Go问答 | 2天前 | channel · 并发编程 · Go问答 · 背压 · 容量规划 · Goroutine channel 缓冲区 背压 Go问答 buffered channel 并发容量377 收藏
-
Golang · Go问答 | 2天前 | interface · 单元测试 · 架构设计 · repository · Go问答 · 单元测试 架构设计 interface 接口设计 Go问答 调用方定义 Repository212 收藏
-
Golang · Go问答 | 2天前 | JSON · time.Time · 接口设计 · Go问答 · encoding/json · encoding/json API响应 JSON序列化 time.Time omitempty Go问答 omitzero315 收藏
-
Golang · Go问答 | 2天前 | HTTP · Cookie · 浏览器 · cors · Go问答 · SameSite · cookie cors Secure SameSite Go问答 Set-Cookie 跨站请求 credentials246 收藏
-
Golang · Go问答 | 2天前 | 中间件 · Context · Go问答 · 架构模式 · 代码边界 · 中间件 context Context.Value Go问答 WithValue 请求作用域 业务参数269 收藏
-
Golang · Go问答 | 2天前 | JSON · 后端开发 · Go问答 · encoding/json · 接口解析 · JSON解析 encoding/json DisallowUnknownFields Go问答 RawMessage json.Decoder UseNumber151 收藏
-
Golang · Go问答 | 3天前 | HTTP · net/http · Go问答 · 流式响应 · ResponseController · net/http FLUSH 流式响应 Go问答 ResponseController FullDuplex 写超时161 收藏
-
Golang · Go问答 | 3天前 | HTTP · sse · Go问答 · 用户体验 · 流式响应 · Go EventSource SSE Go问答 Server-Sent Events 长任务进度 http.Flusher293 收藏
-
Golang · Go问答 | 3天前 | Timer · 性能优化 · time.After · Go问答 · Go 内存优化 Timer time.After Go问答 time.NewTimer Go1.23384 收藏
-
Golang · Go问答 | 3天前 | go · Context · 并发编程 · 接口超时 · 超时控制 goroutine泄漏 WithTimeout Go context Go问答 CancelFunc477 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习