-
Notifications
You must be signed in to change notification settings - Fork 72
/
request.go
88 lines (71 loc) · 1.92 KB
/
request.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
package gateway
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/pkg/errors"
)
// NewRequest returns a new http.Request from the given Lambda event.
func NewRequest(ctx context.Context, e events.APIGatewayProxyRequest) (*http.Request, error) {
// path
u, err := url.Parse(e.Path)
if err != nil {
return nil, errors.Wrap(err, "parsing path")
}
// querystring
q := u.Query()
for k, v := range e.QueryStringParameters {
q.Set(k, v)
}
for k, values := range e.MultiValueQueryStringParameters {
q[k] = values
}
u.RawQuery = q.Encode()
// base64 encoded body
body := e.Body
if e.IsBase64Encoded {
b, err := base64.StdEncoding.DecodeString(body)
if err != nil {
return nil, errors.Wrap(err, "decoding base64 body")
}
body = string(b)
}
// new request
req, err := http.NewRequest(e.HTTPMethod, u.String(), strings.NewReader(body))
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
// manually set RequestURI because NewRequest is for clients and req.RequestURI is for servers
req.RequestURI = u.RequestURI()
// remote addr
req.RemoteAddr = e.RequestContext.Identity.SourceIP
// header fields
for k, v := range e.Headers {
req.Header.Set(k, v)
}
for k, values := range e.MultiValueHeaders {
req.Header[k] = values
}
// content-length
if req.Header.Get("Content-Length") == "" && body != "" {
req.Header.Set("Content-Length", strconv.Itoa(len(body)))
}
// custom fields
req.Header.Set("X-Request-Id", e.RequestContext.RequestID)
req.Header.Set("X-Stage", e.RequestContext.Stage)
// custom context values
req = req.WithContext(newContext(ctx, e))
// xray support
if traceID := ctx.Value("x-amzn-trace-id"); traceID != nil {
req.Header.Set("X-Amzn-Trace-Id", fmt.Sprintf("%v", traceID))
}
// host
req.URL.Host = req.Header.Get("Host")
req.Host = req.URL.Host
return req, nil
}