-
Notifications
You must be signed in to change notification settings - Fork 0
/
apigatewayutils.go
56 lines (45 loc) · 1.54 KB
/
apigatewayutils.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 lambdautils
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/apex/gateway"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
// higher level handler adapter. ServeApiGatewayProxyRequestUsingHttpHandler() is lower if
// you need to be able to give APIGatewayProxyRequest and get back byte slice & error
type LambdaHttpHandlerAdapter struct {
httpHandler http.Handler
}
// adapts lambda.Handler to Go's http.Handler by translating between API gateway request/responses
func NewLambdaHttpHandlerAdapter(httpHandler http.Handler) lambda.Handler {
return &LambdaHttpHandlerAdapter{httpHandler}
}
func (m *LambdaHttpHandlerAdapter) Invoke(ctx context.Context, payload []byte) ([]byte, error) {
e := &events.APIGatewayProxyRequest{}
if err := json.Unmarshal(payload, e); err != nil {
return nil, fmt.Errorf("APIGatewayProxyRequest unmarshal: %w", err)
}
return ServeApiGatewayProxyRequestUsingHttpHandler(
ctx,
e,
m.httpHandler)
}
// github.com/akrylysov/algnhsa has similar implementation than apex/gateway, but had the
// useful bits non-exported and it used httptest for production code
func ServeApiGatewayProxyRequestUsingHttpHandler(
ctx context.Context,
proxyRequest *events.APIGatewayProxyRequest,
httpHandler http.Handler,
) ([]byte, error) {
request, err := gateway.NewRequest(ctx, *proxyRequest)
if err != nil {
return nil, err
}
response := gateway.NewResponse()
httpHandler.ServeHTTP(response, request)
proxyResponse := response.End()
return json.Marshal(&proxyResponse)
}