forked from awslabs/aws-lambda-go-api-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
360 lines (322 loc) · 12 KB
/
request.go
File metadata and controls
360 lines (322 loc) · 12 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Package core provides utility methods that help convert proxy events
// into an http.Request and http.ResponseWriter
package core
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambdacontext"
)
// CustomHostVariable is the name of the environment variable that contains
// the custom hostname for the request. If this variable is not set the framework
// reverts to `DefaultServerAddress`. The value for a custom host should include
// a protocol: http://my-custom.host.com
const CustomHostVariable = "GO_API_HOST"
// DefaultServerAddress is prepended to the path of each incoming reuqest
const DefaultServerAddress = "https://aws-serverless-go-api.com"
// APIGwContextHeader is the custom header key used to store the
// API Gateway context. To access the Context properties use the
// GetAPIGatewayContext method of the RequestAccessor object.
const APIGwContextHeader = "X-GoLambdaProxy-ApiGw-Context"
// APIGwStageVarsHeader is the custom header key used to store the
// API Gateway stage variables. To access the stage variable values
// use the GetAPIGatewayStageVars method of the RequestAccessor object.
const APIGwStageVarsHeader = "X-GoLambdaProxy-ApiGw-StageVars"
// RequestAccessor objects give access to custom API Gateway properties
// in the request.
type RequestAccessor struct {
stripBasePath string
}
// GetAPIGatewayContext extracts the API Gateway context object from a
// request's custom header.
// Returns a populated events.APIGatewayProxyRequestContext object from
// the request.
func (r *RequestAccessor) GetAPIGatewayContext(req *http.Request) (events.APIGatewayProxyRequestContext, error) {
if req.Header.Get(APIGwContextHeader) == "" {
return events.APIGatewayProxyRequestContext{}, errors.New("No context header in request")
}
context := events.APIGatewayProxyRequestContext{}
err := json.Unmarshal([]byte(req.Header.Get(APIGwContextHeader)), &context)
if err != nil {
log.Println("Erorr while unmarshalling context")
log.Println(err)
return events.APIGatewayProxyRequestContext{}, err
}
return context, nil
}
// GetAPIGatewayStageVars extracts the API Gateway stage variables from a
// request's custom header.
// Returns a map[string]string of the stage variables and their values from
// the request.
func (r *RequestAccessor) GetAPIGatewayStageVars(req *http.Request) (map[string]string, error) {
stageVars := make(map[string]string)
if req.Header.Get(APIGwStageVarsHeader) == "" {
return stageVars, errors.New("No stage vars header in request")
}
err := json.Unmarshal([]byte(req.Header.Get(APIGwStageVarsHeader)), &stageVars)
if err != nil {
log.Println("Erorr while unmarshalling stage variables")
log.Println(err)
return stageVars, err
}
return stageVars, nil
}
// StripBasePath instructs the RequestAccessor object that the given base
// path should be removed from the request path before sending it to the
// framework for routing. This is used when API Gateway is configured with
// base path mappings in custom domain names.
func (r *RequestAccessor) StripBasePath(basePath string) string {
if strings.Trim(basePath, " ") == "" {
r.stripBasePath = ""
return ""
}
newBasePath := basePath
if !strings.HasPrefix(newBasePath, "/") {
newBasePath = "/" + newBasePath
}
if strings.HasSuffix(newBasePath, "/") {
newBasePath = newBasePath[:len(newBasePath)-1]
}
r.stripBasePath = newBasePath
return newBasePath
}
// ProxyEventToHTTPRequest converts an API Gateway proxy event into a http.Request object.
// Returns the populated http request with additional two custom headers for the stage variables and API Gateway context.
// To access these properties use the GetAPIGatewayStageVars and GetAPIGatewayContext method of the RequestAccessor object.
func (r *RequestAccessor) ProxyEventToHTTPRequest(req events.APIGatewayProxyRequest) (*http.Request, error) {
httpRequest, err := r.EventToRequest(req)
if err != nil {
log.Println(err)
return nil, err
}
return addToHeader(httpRequest, req)
}
func (r *RequestAccessor) ProxyEventToHTTPRequestV2(req events.APIGatewayV2HTTPRequest) (*http.Request, error) {
httpRequest, err := r.EventToRequestV2(req)
if err != nil {
log.Println(err)
return nil, err
}
return addToHeaderV2(httpRequest, req)
}
// EventToRequestWithContext converts an API Gateway proxy event and context into an http.Request object.
// Returns the populated http request with lambda context, stage variables and APIGatewayProxyRequestContext as part of its context.
// Access those using GetAPIGatewayContextFromContext, GetStageVarsFromContext and GetRuntimeContextFromContext functions in this package.
func (r *RequestAccessor) EventToRequestWithContext(ctx context.Context, req events.APIGatewayProxyRequest) (*http.Request, error) {
httpRequest, err := r.EventToRequest(req)
if err != nil {
log.Println(err)
return nil, err
}
return addToContext(ctx, httpRequest, req), nil
}
func (r *RequestAccessor) EventToRequestWithContextV2(ctx context.Context, req events.APIGatewayV2HTTPRequest) (*http.Request, error) {
httpRequest, err := r.EventToRequestV2(req)
if err != nil {
log.Println(err)
return nil, err
}
return addToContextV2(ctx, httpRequest, req), nil
}
// EventToRequest converts an API Gateway proxy event into an http.Request object.
// Returns the populated request maintaining headers
func (r *RequestAccessor) EventToRequest(req events.APIGatewayProxyRequest) (*http.Request, error) {
decodedBody := []byte(req.Body)
if req.IsBase64Encoded {
base64Body, err := base64.StdEncoding.DecodeString(req.Body)
if err != nil {
return nil, err
}
decodedBody = base64Body
}
path := req.Path
if r.stripBasePath != "" && len(r.stripBasePath) > 1 {
if strings.HasPrefix(path, r.stripBasePath) {
path = strings.Replace(path, r.stripBasePath, "", 1)
}
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
serverAddress := DefaultServerAddress
if customAddress, ok := os.LookupEnv(CustomHostVariable); ok {
serverAddress = customAddress
}
path = serverAddress + path
if len(req.MultiValueQueryStringParameters) > 0 {
queryString := ""
for q, l := range req.MultiValueQueryStringParameters {
for _, v := range l {
if queryString != "" {
queryString += "&"
}
queryString += url.QueryEscape(q) + "=" + url.QueryEscape(v)
}
}
path += "?" + queryString
} else if len(req.QueryStringParameters) > 0 {
// Support `QueryStringParameters` for backward compatibility.
// https://github.com/awslabs/aws-lambda-go-api-proxy/issues/37
queryString := ""
for q := range req.QueryStringParameters {
if queryString != "" {
queryString += "&"
}
queryString += url.QueryEscape(q) + "=" + url.QueryEscape(req.QueryStringParameters[q])
}
path += "?" + queryString
}
httpRequest, err := http.NewRequest(
strings.ToUpper(req.HTTPMethod),
path,
bytes.NewReader(decodedBody),
)
if err != nil {
fmt.Printf("Could not convert request %s:%s to http.Request\n", req.HTTPMethod, req.Path)
log.Println(err)
return nil, err
}
for h := range req.Headers {
httpRequest.Header.Add(h, req.Headers[h])
}
return httpRequest, nil
}
func (r *RequestAccessor) EventToRequestV2(req events.APIGatewayV2HTTPRequest) (*http.Request, error) {
decodedBody := []byte(req.Body)
if req.IsBase64Encoded {
base64Body, err := base64.StdEncoding.DecodeString(req.Body)
if err != nil {
return nil, err
}
decodedBody = base64Body
}
path := req.RequestContext.HTTP.Path
if r.stripBasePath != "" && len(r.stripBasePath) > 1 {
if strings.HasPrefix(path, r.stripBasePath) {
path = strings.Replace(path, r.stripBasePath, "", 1)
}
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
serverAddress := DefaultServerAddress
if customAddress, ok := os.LookupEnv(CustomHostVariable); ok {
serverAddress = customAddress
}
path = serverAddress + path
if len(req.QueryStringParameters) > 0 {
queryString := ""
for q, l := range req.QueryStringParameters {
values := strings.Split(l, ",")
for _, v := range values {
if queryString != "" {
queryString += "&"
}
queryString += url.QueryEscape(q) + "=" + url.QueryEscape(v)
}
}
path += "?" + queryString
} else if len(req.QueryStringParameters) > 0 {
// Support `QueryStringParameters` for backward compatibility.
// https://github.com/awslabs/aws-lambda-go-api-proxy/issues/37
queryString := ""
for q := range req.QueryStringParameters {
if queryString != "" {
queryString += "&"
}
queryString += url.QueryEscape(q) + "=" + url.QueryEscape(req.QueryStringParameters[q])
}
path += "?" + queryString
}
httpRequest, err := http.NewRequest(
strings.ToUpper(req.RequestContext.HTTP.Method),
path,
bytes.NewReader(decodedBody),
)
if err != nil {
fmt.Printf("Could not convert request %s:%s to http.Request\n", req.RequestContext.HTTP.Method, req.RequestContext.HTTP.Path)
log.Println(err)
return nil, err
}
for h := range req.Headers {
httpRequest.Header.Add(h, req.Headers[h])
}
return httpRequest, nil
}
func addToHeader(req *http.Request, apiGwRequest events.APIGatewayProxyRequest) (*http.Request, error) {
stageVars, err := json.Marshal(apiGwRequest.StageVariables)
if err != nil {
log.Println("Could not marshal stage variables for custom header")
return nil, err
}
req.Header.Add(APIGwStageVarsHeader, string(stageVars))
apiGwContext, err := json.Marshal(apiGwRequest.RequestContext)
if err != nil {
log.Println("Could not Marshal API GW context for custom header")
return req, err
}
req.Header.Add(APIGwContextHeader, string(apiGwContext))
return req, nil
}
func addToHeaderV2(req *http.Request, apiGwRequest events.APIGatewayV2HTTPRequest) (*http.Request, error) {
stageVars, err := json.Marshal(apiGwRequest.StageVariables)
if err != nil {
log.Println("Could not marshal stage variables for custom header")
return nil, err
}
req.Header.Add(APIGwStageVarsHeader, string(stageVars))
apiGwContext, err := json.Marshal(apiGwRequest.RequestContext)
if err != nil {
log.Println("Could not Marshal API GW context for custom header")
return req, err
}
req.Header.Add(APIGwContextHeader, string(apiGwContext))
return req, nil
}
func addToContext(ctx context.Context, req *http.Request, apiGwRequest events.APIGatewayProxyRequest) *http.Request {
lc, _ := lambdacontext.FromContext(ctx)
rc := requestContext{lambdaContext: lc, gatewayProxyContext: apiGwRequest.RequestContext, stageVars: apiGwRequest.StageVariables}
ctx = context.WithValue(ctx, ctxKey{}, rc)
return req.WithContext(ctx)
}
func addToContextV2(ctx context.Context, req *http.Request, apiGwRequest events.APIGatewayV2HTTPRequest) *http.Request {
lc, _ := lambdacontext.FromContext(ctx)
rc := requestContextV2{lambdaContext: lc, gatewayProxyContext: apiGwRequest.RequestContext, stageVars: apiGwRequest.StageVariables}
ctx = context.WithValue(ctx, ctxKey{}, rc)
return req.WithContext(ctx)
}
// GetAPIGatewayContextFromContext retrieve APIGatewayProxyRequestContext from context.Context
func GetAPIGatewayContextFromContext(ctx context.Context) (events.APIGatewayProxyRequestContext, bool) {
v, ok := ctx.Value(ctxKey{}).(requestContext)
return v.gatewayProxyContext, ok
}
// GetRuntimeContextFromContext retrieve Lambda Runtime Context from context.Context
func GetRuntimeContextFromContext(ctx context.Context) (*lambdacontext.LambdaContext, bool) {
v, ok := ctx.Value(ctxKey{}).(requestContext)
return v.lambdaContext, ok
}
// GetStageVarsFromContext retrieve stage variables from context
func GetStageVarsFromContext(ctx context.Context) (map[string]string, bool) {
v, ok := ctx.Value(ctxKey{}).(requestContext)
return v.stageVars, ok
}
type ctxKey struct{}
type requestContext struct {
lambdaContext *lambdacontext.LambdaContext
gatewayProxyContext events.APIGatewayProxyRequestContext
stageVars map[string]string
}
type requestContextV2 struct {
lambdaContext *lambdacontext.LambdaContext
gatewayProxyContext events.APIGatewayV2HTTPRequestContext
stageVars map[string]string
}