This repository has been archived by the owner on Sep 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gateway.go
56 lines (46 loc) · 1.46 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
package apigo
import (
"context"
"net/http"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
// Gateway mimics the http.Server definition and takes care of proxying
// AWS Lambda event to http.Request via Proxy and then handling it using Handler
type Gateway struct {
Proxy Proxy
Handler http.Handler
}
// NewGateway creates new Gateway, which utilizes handler
// (or http.DefaultServeMux if nil passed) as a Gateway.Handler and
// apigo.http.DefaultProxy as a Gateway.Proxy.
func NewGateway(host string, handler http.Handler) *Gateway {
if handler == nil {
handler = http.DefaultServeMux
}
return &Gateway{
Handler: handler,
Proxy: &DefaultProxy{host},
}
}
// ListenAndServe is a drop-in replacement for http.ListenAndServe for use
// within AWS Lambda.
func ListenAndServe(host string, h http.Handler) {
NewGateway(host, h).ListenAndServe()
}
// ListenAndServe registers a listener of AWS Lambda events.
func (g *Gateway) ListenAndServe() {
lambda.Start(g.Serve)
}
// Serve handles incoming event from AWS Lambda by wraping them into
// http.Request which is further processed by http.Handler to reply
// as a APIGatewayProxyResponse.
func (g *Gateway) Serve(ctx context.Context, e events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
r, err := g.Proxy.Transform(ctx, e)
if err != nil {
return events.APIGatewayProxyResponse{}, err
}
w := NewResponse()
g.Handler.ServeHTTP(w, r)
return w.End(), nil
}