forked from awslabs/aws-lambda-go-api-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adapter.go
167 lines (138 loc) · 5.29 KB
/
adapter.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// Package fiberadapter adds Fiber support for the aws-severless-go-api library.
// Uses the core package behind the scenes and exposes the New method to
// get a new instance and Proxy method to send request to the Fiber app.
package fiberadapter
import (
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
"github.com/valyala/fasthttp"
"github.com/catdevman/aws-lambda-go-api-proxy/core"
)
// FiberLambda makes it easy to send API Gateway proxy events to a fiber.App.
// The library transforms the proxy event into an HTTP request and then
// creates a proxy response object from the *fiber.Ctx
type FiberLambda struct {
core.RequestAccessor
v2 core.RequestAccessorV2
app *fiber.App
}
// New creates a new instance of the FiberLambda object.
// Receives an initialized *fiber.App object - normally created with fiber.New().
// It returns the initialized instance of the FiberLambda object.
func New(app *fiber.App) *FiberLambda {
return &FiberLambda{
app: app,
}
}
// Proxy receives an API Gateway proxy event, transforms it into an http.Request
// object, and sends it to the fiber.App for routing.
// It returns a proxy response object generated from the http.ResponseWriter.
func (f *FiberLambda) Proxy(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
fiberRequest, err := f.ProxyEventToHTTPRequest(req)
return f.proxyInternal(fiberRequest, err)
}
// ProxyV2 is just same as Proxy() but for APIGateway HTTP payload v2
func (f *FiberLambda) ProxyV2(req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
fiberRequest, err := f.v2.ProxyEventToHTTPRequest(req)
return f.proxyInternalV2(fiberRequest, err)
}
// ProxyWithContext receives context and an API Gateway proxy event,
// transforms them into an http.Request object, and sends it to the echo.Echo for routing.
// It returns a proxy response object generated from the http.ResponseWriter.
func (f *FiberLambda) ProxyWithContext(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
fiberRequest, err := f.EventToRequestWithContext(ctx, req)
return f.proxyInternal(fiberRequest, err)
}
// ProxyWithContextV2 is just same as ProxyWithContext() but for APIGateway HTTP payload v2
func (f *FiberLambda) ProxyWithContextV2(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
fiberRequest, err := f.v2.EventToRequestWithContext(ctx, req)
return f.proxyInternalV2(fiberRequest, err)
}
func (f *FiberLambda) proxyInternal(req *http.Request, err error) (events.APIGatewayProxyResponse, error) {
if err != nil {
return core.GatewayTimeout(), core.NewLoggedError("Could not convert proxy event to request: %v", err)
}
resp := core.NewProxyResponseWriter()
f.adaptor(resp, req)
proxyResponse, err := resp.GetProxyResponse()
if err != nil {
return core.GatewayTimeout(), core.NewLoggedError("Error while generating proxy response: %v", err)
}
return proxyResponse, nil
}
func (f *FiberLambda) proxyInternalV2(req *http.Request, err error) (events.APIGatewayV2HTTPResponse, error) {
if err != nil {
return core.GatewayTimeoutV2(), core.NewLoggedError("Could not convert proxy event to request: %v", err)
}
resp := core.NewProxyResponseWriterV2()
f.adaptor(resp, req)
proxyResponse, err := resp.GetProxyResponse()
if err != nil {
return core.GatewayTimeoutV2(), core.NewLoggedError("Error while generating proxy response: %v", err)
}
return proxyResponse, nil
}
func (f *FiberLambda) adaptor(w http.ResponseWriter, r *http.Request) {
// New fasthttp request
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
// Convert net/http -> fasthttp request
body, err := io.ReadAll(r.Body)
if err != nil {
log.Println(err)
http.Error(w, utils.StatusMessage(fiber.StatusInternalServerError), fiber.StatusInternalServerError)
return
}
req.Header.SetContentLength(len(body))
_, _ = req.BodyWriter().Write(body)
req.Header.SetMethod(r.Method)
req.SetRequestURI(r.RequestURI)
req.SetHost(r.Host)
for key, val := range r.Header {
for _, v := range val {
switch key {
case fiber.HeaderHost,
fiber.HeaderContentType,
fiber.HeaderUserAgent,
fiber.HeaderContentLength,
fiber.HeaderConnection:
req.Header.Set(key, v)
default:
req.Header.Add(key, v)
}
}
}
// We need to make sure the net.ResolveTCPAddr call works as it expects a port
addrWithPort := r.RemoteAddr
if !strings.Contains(r.RemoteAddr, ":") {
addrWithPort = r.RemoteAddr + ":80" // assuming a default port
}
remoteAddr, err := net.ResolveTCPAddr("tcp", addrWithPort)
if err != nil {
fmt.Printf("could not resolve TCP address for addr %s\n", r.RemoteAddr)
log.Println(err)
http.Error(w, utils.StatusMessage(fiber.StatusInternalServerError), fiber.StatusInternalServerError)
return
}
// New fasthttp Ctx
var fctx fasthttp.RequestCtx
fctx.Init(req, remoteAddr, nil)
// Pass RequestCtx to Fiber router
f.app.Handler()(&fctx)
// Set response headers
fctx.Response.Header.VisitAll(func(k, v []byte) {
w.Header().Add(utils.UnsafeString(k), utils.UnsafeString(v))
})
// Set response statuscode
w.WriteHeader(fctx.Response.StatusCode())
// Set response body
_, _ = w.Write(fctx.Response.Body())
}