-
Notifications
You must be signed in to change notification settings - Fork 40
/
adapter.go
65 lines (57 loc) · 1.65 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package algnhsa
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"github.com/aws/aws-lambda-go/lambda"
)
// New returns a new lambda handler for the given http.Handler.
// It is up to the caller of New to run lamdba.Start(handler) with the returned handler.
func New(handler http.Handler, opts *Options) lambda.Handler {
if handler == nil {
handler = http.DefaultServeMux
}
if opts == nil {
opts = defaultOptions
}
opts.setBinaryContentTypeMap()
return lambdaHandler{httpHandler: handler, opts: opts}
}
var defaultOptions = &Options{}
type lambdaHandler struct {
httpHandler http.Handler
opts *Options
}
func (handler lambdaHandler) Invoke(ctx context.Context, payload []byte) ([]byte, error) {
resp, err := handler.handleEvent(ctx, payload)
if err != nil {
return nil, err
}
if handler.opts.DebugLog {
fmt.Printf("Response: %+v", resp)
}
return json.Marshal(resp)
}
func (handler lambdaHandler) handleEvent(ctx context.Context, payload []byte) (lambdaResponse, error) {
if handler.opts.DebugLog {
fmt.Printf("Request: %s", payload)
}
eventReq, err := newLambdaRequest(ctx, payload, handler.opts)
if err != nil {
return lambdaResponse{}, err
}
r, err := newHTTPRequest(eventReq)
if err != nil {
return lambdaResponse{}, err
}
w := httptest.NewRecorder()
handler.httpHandler.ServeHTTP(w, r)
return newLambdaResponse(w, handler.opts.binaryContentTypeMap, eventReq.requestType)
}
// ListenAndServe starts the AWS Lambda runtime (aws-lambda-go lambda.Start) with a given handler.
func ListenAndServe(handler http.Handler, opts *Options) {
lambdaHandler := New(handler, opts)
lambda.StartHandler(lambdaHandler)
}