-
Notifications
You must be signed in to change notification settings - Fork 72
/
gateway.go
59 lines (45 loc) · 1.23 KB
/
gateway.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
// Package gateway provides a drop-in replacement for net/http.ListenAndServe for use in AWS Lambda & API Gateway.
package gateway
import (
"context"
"encoding/json"
"net/http"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
// ListenAndServe is a drop-in replacement for
// http.ListenAndServe for use within AWS Lambda.
//
// ListenAndServe always returns a non-nil error.
func ListenAndServe(addr string, h http.Handler) error {
if h == nil {
h = http.DefaultServeMux
}
gw := NewGateway(h)
lambda.StartHandler(gw)
return nil
}
// NewGateway creates a gateway using the provided http.Handler enabling use in existing aws-lambda-go
// projects
func NewGateway(h http.Handler) *Gateway {
return &Gateway{h: h}
}
// Gateway wrap a http handler to enable use as a lambda.Handler
type Gateway struct {
h http.Handler
}
// Invoke Handler implementation
func (gw *Gateway) Invoke(ctx context.Context, payload []byte) ([]byte, error) {
evt := events.APIGatewayProxyRequest{}
if err := json.Unmarshal(payload, &evt); err != nil {
return nil, err
}
r, err := NewRequest(ctx, evt)
if err != nil {
return nil, err
}
w := NewResponse()
gw.h.ServeHTTP(w, r)
resp := w.End()
return json.Marshal(&resp)
}