-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
72 lines (58 loc) · 1.52 KB
/
server.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
package glamor
import (
"context"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/labstack/echo"
)
type lambdaFn func(context.Context, events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)
func WrapServer(e *echo.Echo) lambdaFn {
return func(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
body := strings.NewReader(request.Body)
req := httptest.NewRequest(request.HTTPMethod, request.Path, body)
for k, v := range request.Headers {
req.Header.Add(k, v)
}
query := url.Values{}
for k, v := range request.QueryStringParameters {
query.Add(k, v)
}
rawQuery := query.Encode()
if rawQuery != "" {
req.URL.RawQuery = rawQuery
}
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
res := rec.Result()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusInternalServerError,
Body: err.Error(),
Headers: headersToMap(res.Header),
}, nil
}
return events.APIGatewayProxyResponse{
StatusCode: res.StatusCode,
Body: string(b),
Headers: headersToMap(res.Header),
}, nil
}
}
func headersToMap(headers http.Header) map[string]string {
result := make(map[string]string)
for key, values := range headers {
var resultValue string
if len(values) == 0 {
resultValue = ""
} else {
resultValue = values[0]
}
result[key] = resultValue
}
return result
}