-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshim.go
78 lines (63 loc) · 2.19 KB
/
shim.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package shim
import (
"context"
"net/http"
"github.com/aws/aws-lambda-go/events"
)
// Handler is an interface for accepting and responding to API Gateway integration requests
type Handler interface {
Handle(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)
}
// Shim provides a thin layer between your traditional http.Handler based application and AWS Lambda + API Gateway.
type Shim struct {
Handler http.Handler
Log Log
}
// New returns an initialized Shim with the provided http.Handler. If not http.Handler is provided New will use http.DefaultServiceMux
func New(h http.Handler, options ...func(*Shim)) Handler {
if h == nil {
h = http.DefaultServeMux
}
s := &Shim{
Handler: h,
}
for _, option := range options {
option(s)
}
return s
}
// SetDebugLogger is an option function to set the debug logger on a Shim. The debug logger gives insight into the event received from
// APIGateway and how shim transforms the request and response.
func SetDebugLogger(l Log) func(*Shim) {
return func(s *Shim) {
s.Log = l
}
}
// Handle converts an APIGatewayProxyRequest converts an APIGatewayProxyRequest into an http.Request and passes it to the given http.Handler
// along with a ResponseWriter. The response from the handler is converted into an APIGatewayProxyResponse.
func (s *Shim) Handle(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
s.printf("event request: %+v\n", request)
httpReq, err := NewHTTPRequest(ctx, request)
if err != nil {
s.println("received an error while constructing http request from API Gateway request event")
return events.APIGatewayProxyResponse{}, err
}
s.printf("http request: %+v", httpReq)
rw := NewResponseWriter()
s.println("calling ServeHTTP on shim handler")
s.Handler.ServeHTTP(rw, httpReq)
s.printf("received response: %+v\n", rw)
resp := NewAPIGatewayProxyResponse(rw)
s.printf("api gateway proxy response: %+v\n", resp)
return resp, nil
}
func (s *Shim) println(v ...interface{}) {
if s.Log != nil {
s.Log.Println(v...)
}
}
func (s *Shim) printf(format string, v ...interface{}) {
if s.Log != nil {
s.Log.Printf(format, v...)
}
}