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