|
| 1 | +package chiadapter |
| 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/go-chi/chi/v5" |
| 10 | +) |
| 11 | + |
| 12 | +// ChiLambdaV2 makes it easy to send API Gateway proxy V2 events to a Chi |
| 13 | +// Mux. The library transforms the proxy event into an HTTP request and then |
| 14 | +// creates a proxy response object from the http.ResponseWriter |
| 15 | +type ChiLambdaV2 struct { |
| 16 | + core.RequestAccessorV2 |
| 17 | + |
| 18 | + chiMux *chi.Mux |
| 19 | +} |
| 20 | + |
| 21 | +// New creates a new instance of the ChiLambdaV2 object. |
| 22 | +// Receives an initialized *chi.Mux object - normally created with chi.NewRouter(). |
| 23 | +// It returns the initialized instance of the ChiLambdaV2 object. |
| 24 | +func NewV2(chi *chi.Mux) *ChiLambdaV2 { |
| 25 | + return &ChiLambdaV2{chiMux: chi} |
| 26 | +} |
| 27 | + |
| 28 | +// Proxy receives an API Gateway proxy V2 event, transforms it into an http.Request |
| 29 | +// object, and sends it to the chi.Mux for routing. |
| 30 | +// It returns a proxy response object generated from the http.ResponseWriter. |
| 31 | +func (g *ChiLambdaV2) Proxy(req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) { |
| 32 | + chiRequest, err := g.ProxyEventToHTTPRequest(req) |
| 33 | + return g.proxyInternal(chiRequest, 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 chi.Mux for routing. |
| 38 | +// It returns a proxy response object generated from the http.ResponseWriter. |
| 39 | +func (g *ChiLambdaV2) ProxyWithContextV2(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) { |
| 40 | + chiRequest, err := g.EventToRequestWithContext(ctx, req) |
| 41 | + return g.proxyInternal(chiRequest, err) |
| 42 | +} |
| 43 | + |
| 44 | +func (g *ChiLambdaV2) proxyInternal(chiRequest *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 | + g.chiMux.ServeHTTP(http.ResponseWriter(respWriter), chiRequest) |
| 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