|
| 1 | +// Packge chilambda add Chi support for the aws-severless-go-api library. |
| 2 | +// Uses the core package behind the scenes and exposes the New method to |
| 3 | +// get a new instance and Proxy method to send request to the Chi mux. |
| 4 | +package chiadapter |
| 5 | + |
| 6 | +import ( |
| 7 | + "net/http" |
| 8 | + |
| 9 | + "github.com/aws/aws-lambda-go/events" |
| 10 | + "github.com/awslabs/aws-lambda-go-api-proxy/core" |
| 11 | + "github.com/go-chi/chi" |
| 12 | +) |
| 13 | + |
| 14 | +// ChiLambda makes it easy to send API Gateway proxy events to a Chi |
| 15 | +// Mux. The library transforms the proxy event into an HTTP request and then |
| 16 | +// creates a proxy response object from the http.ResponseWriter |
| 17 | +type ChiLambda struct { |
| 18 | + core.RequestAccessor |
| 19 | + |
| 20 | + chiMux *chi.Mux |
| 21 | +} |
| 22 | + |
| 23 | +// New creates a new instance of the ChiLambda object. |
| 24 | +// Receives an initialized *chi.Mux object - normally created with chi.NewRouter(). |
| 25 | +// It returns the initialized instance of the ChiLambda object. |
| 26 | +func New(chi *chi.Mux) *ChiLambda { |
| 27 | + return &ChiLambda{chiMux: chi} |
| 28 | +} |
| 29 | + |
| 30 | +// Proxy receives an API Gateway proxy event, transforms it into an http.Request |
| 31 | +// object, and sends it to the chi.Mux for routing. |
| 32 | +// It returns a proxy response object gneerated from the http.ResponseWriter. |
| 33 | +func (g *ChiLambda) Proxy(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { |
| 34 | + chiRequest, err := g.ProxyEventToHTTPRequest(req) |
| 35 | + |
| 36 | + if err != nil { |
| 37 | + return core.GatewayTimeout(), core.NewLoggedError("Could not convert proxy event to request: %v", err) |
| 38 | + } |
| 39 | + |
| 40 | + respWriter := core.NewProxyResponseWriter() |
| 41 | + g.chiMux.ServeHTTP(http.ResponseWriter(respWriter), chiRequest) |
| 42 | + |
| 43 | + proxyResponse, err := respWriter.GetProxyResponse() |
| 44 | + if err != nil { |
| 45 | + return core.GatewayTimeout(), core.NewLoggedError("Error while generating proxy response: %v", err) |
| 46 | + } |
| 47 | + |
| 48 | + return proxyResponse, nil |
| 49 | +} |
0 commit comments