/
lambda_handler.go
91 lines (73 loc) · 2.04 KB
/
lambda_handler.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
79
80
81
82
83
84
85
86
87
88
89
90
91
package handlers
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/aws/aws-lambda-go/events"
)
func lambdaStatus(code int, err error) (events.APIGatewayV2HTTPResponse, error) {
buff, _ := marshalStruct(struct {
Result string `json:"result"`
Timestamp string `json:"timestamp"`
}{
Result: http.StatusText(code),
Timestamp: time.Now().Format(time.RFC3339),
})
res := events.APIGatewayV2HTTPResponse{
StatusCode: code,
Headers: map[string]string{
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json;charset=utf-8",
},
Body: string(buff),
}
return res, err
}
func Lambda(
ctx context.Context,
req events.APIGatewayV2HTTPRequest) (
events.APIGatewayV2HTTPResponse, error) {
httpMethod := strings.ToUpper(req.RequestContext.HTTP.Method)
if httpMethod == http.MethodGet &&
req.RawPath == fmt.Sprintf("/%s/", req.RequestContext.Stage) {
var buffer strings.Builder
if err := playgroundTemplate.Execute(&buffer, struct {
Endpoint string
}{
Endpoint: fmt.Sprintf("/%s/graphql", req.RequestContext.Stage),
}); err != nil {
return lambdaStatus(http.StatusInternalServerError, err)
}
return events.APIGatewayV2HTTPResponse{
StatusCode: http.StatusOK,
Headers: map[string]string{
"Content-Type": "text/html;charset=utf-8",
},
Body: buffer.String(),
}, nil
}
if httpMethod != http.MethodPost ||
req.RawPath != fmt.Sprintf("/%s/graphql", req.RequestContext.Stage) {
return lambdaStatus(http.StatusNotFound, nil)
}
body := strings.TrimSpace(req.Body)
ret, statusCode := executeGraphQL(ctx, body)
if statusCode != http.StatusOK {
return lambdaStatus(http.StatusBadRequest, nil)
}
buff, err := marshalStruct(ret)
if err != nil {
return lambdaStatus(http.StatusInternalServerError, err)
}
res := events.APIGatewayV2HTTPResponse{
StatusCode: http.StatusOK,
Headers: map[string]string{
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json;charset=utf-8",
},
Body: string(buff),
}
return res, nil
}