-
Notifications
You must be signed in to change notification settings - Fork 4
/
lambda.go
96 lines (81 loc) · 2.05 KB
/
lambda.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
92
93
94
95
96
package fasthttplambda
import (
"encoding/base64"
"net"
"net/url"
"github.com/aws/aws-lambda-go/events"
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttputil"
)
var Router *fasthttprouter.Router
type ProxyOutput struct {
IsBase64Encoded bool `json:"isBase64Encoded"`
StatusCode int `json:"statusCode"`
Body string `json:"body"`
Headers map[string]string `json:"headers"`
}
func server(l net.Listener) {
conn, err := l.Accept()
if err != nil {
panic(err)
}
err = fasthttp.ServeConn(conn, Router.Handler)
if err != nil {
panic(err)
}
err = l.Close()
if err != nil {
panic(err)
}
}
func Handle(event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
//func Handle(event *apigatewayproxyevt.Event, ctx *runtime.Context) (*ProxyOutput, error) {
l := fasthttputil.NewInmemoryListener()
go server(l)
var (
req = fasthttp.AcquireRequest()
resp = fasthttp.AcquireResponse()
)
uri := url.URL{}
uri.Path = event.Path
uri.Host = "localhost"
vals := url.Values{}
for k, v := range event.QueryStringParameters {
vals.Set(k, v)
}
uri.RawQuery = vals.Encode()
req.SetRequestURI(uri.RequestURI())
req.SetHost("localhost")
if event.IsBase64Encoded {
body, err := base64.StdEncoding.DecodeString(event.Body)
if err != nil {
return events.APIGatewayProxyResponse{}, err
}
req.SetBody(body)
} else {
req.SetBody([]byte(event.Body))
}
for k, v := range event.Headers {
req.Header.Add(k, v)
}
req.Header.SetMethod(event.HTTPMethod)
client := fasthttp.Client{
Dial: func(string) (net.Conn, error) { return l.Dial() },
}
err := client.Do(req, resp)
if err != nil {
panic(err)
}
var header = map[string]string{}
resp.Header.VisitAll(func(k, v []byte) {
header[string(k)] = string(v)
})
var output = events.APIGatewayProxyResponse{
IsBase64Encoded: false,
StatusCode: resp.StatusCode(),
Body: string(resp.Body()),
Headers: header,
}
return output, nil
}