|
| 1 | +package echoadapter |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net/http" |
| 6 | + |
| 7 | + "github.com/aws/aws-lambda-go/events" |
| 8 | + "github.com/awslabs/aws-lambda-go-api-proxy/core" |
| 9 | + "github.com/labstack/echo/v4" |
| 10 | +) |
| 11 | + |
| 12 | +// EchoLambdaV2 makes it easy to send API Gateway proxy V2 events to a echo.Echo. |
| 13 | +// The library transforms the proxy event into an HTTP request and then |
| 14 | +// creates a proxy response object from the http.ResponseWriter |
| 15 | +type EchoLambdaV2 struct { |
| 16 | + core.RequestAccessorV2 |
| 17 | + |
| 18 | + Echo *echo.Echo |
| 19 | +} |
| 20 | + |
| 21 | +// NewV2 creates a new instance of the EchoLambda object. |
| 22 | +// Receives an initialized *echo.Echo object - normally created with echo.New(). |
| 23 | +// It returns the initialized instance of the EchoLambdaV2 object. |
| 24 | +func NewV2(e *echo.Echo) *EchoLambdaV2 { |
| 25 | + return &EchoLambdaV2{Echo: e} |
| 26 | +} |
| 27 | + |
| 28 | +// Proxy receives an API Gateway proxy V2 event, transforms it into an http.Request |
| 29 | +// object, and sends it to the echo.Echo for routing. |
| 30 | +// It returns a proxy response object generated from the http.ResponseWriter. |
| 31 | +func (e *EchoLambdaV2) Proxy(req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) { |
| 32 | + echoRequest, err := e.ProxyEventToHTTPRequest(req) |
| 33 | + return e.proxyInternal(echoRequest, err) |
| 34 | +} |
| 35 | + |
| 36 | +// ProxyWithContext receives context and an API Gateway proxy V2 event, |
| 37 | +// transforms them into an http.Request object, and sends it to the echo.Echo for routing. |
| 38 | +// It returns a proxy response object generated from the http.ResponseWriter. |
| 39 | +func (e *EchoLambdaV2) ProxyWithContext(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) { |
| 40 | + echoRequest, err := e.EventToRequestWithContext(ctx, req) |
| 41 | + return e.proxyInternal(echoRequest, err) |
| 42 | +} |
| 43 | + |
| 44 | +func (e *EchoLambdaV2) proxyInternal(req *http.Request, err error) (events.APIGatewayV2HTTPResponse, error) { |
| 45 | + |
| 46 | + if err != nil { |
| 47 | + return core.GatewayTimeoutV2(), core.NewLoggedError("Could not convert proxy event to request: %v", err) |
| 48 | + } |
| 49 | + |
| 50 | + respWriter := core.NewProxyResponseWriterV2() |
| 51 | + e.Echo.ServeHTTP(http.ResponseWriter(respWriter), req) |
| 52 | + |
| 53 | + proxyResponse, err := respWriter.GetProxyResponse() |
| 54 | + if err != nil { |
| 55 | + return core.GatewayTimeoutV2(), core.NewLoggedError("Error while generating proxy response: %v", err) |
| 56 | + } |
| 57 | + |
| 58 | + return proxyResponse, nil |
| 59 | +} |
0 commit comments