This repository has been archived by the owner on Aug 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequest.go
81 lines (73 loc) · 2.26 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
package gluo
import (
"context"
"encoding/base64"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambdacontext"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
func mustBuildURL(event events.APIGatewayProxyRequest) string {
query := url.Values{}
for name, value := range event.QueryStringParameters {
query.Add(name, value)
}
u := url.URL{
Scheme: event.Headers["X-Forwarded-Proto"],
Host: event.Headers["Host"],
Path: event.Path,
RawQuery: query.Encode(),
}
return u.String()
}
func getBodyReader(event events.APIGatewayProxyRequest) (io.Reader, error) {
var body io.Reader = strings.NewReader(event.Body)
if event.IsBase64Encoded {
body = base64.NewDecoder(base64.StdEncoding, body)
}
return body, nil
}
// An unexported type to be used as the key for types in this package.
type contextKey struct{}
// The key for a LambdaContext in Contexts.
var reqCtxKey = &contextKey{}
// APIGatewayContext returns the APIGatewayProxyRequestContext value stored in ctx.
func APIGatewayContext(ctx context.Context) (events.APIGatewayProxyRequestContext, bool) {
c, ok := ctx.Value(reqCtxKey).(events.APIGatewayProxyRequestContext)
return c, ok
}
// LambdaContext return the LambdaContext value stored in ctx.
func LambdaContext(ctx context.Context) (*lambdacontext.LambdaContext, bool) {
return lambdacontext.FromContext(ctx)
}
func request(ctx context.Context, event events.APIGatewayProxyRequest) (*http.Request, error) {
body, err := getBodyReader(event)
if err != nil {
return nil, err
}
req, err := http.NewRequest(event.HTTPMethod, mustBuildURL(event), body)
if err != nil {
return nil, err
}
ctx = context.WithValue(ctx, reqCtxKey, event.RequestContext)
req = req.WithContext(ctx)
req.Header = http.Header{}
for name, value := range event.Headers {
req.Header.Add(name, value)
}
if req.ContentLength > -1 {
req.Header.Set("Content-Length", strconv.FormatInt(req.ContentLength, 10))
}
req.Header.Set("X-Request-ID", event.RequestContext.RequestID)
req.Header.Set("X-Stage", event.RequestContext.Stage)
// AWS X-Ray
if traceID := ctx.Value("x-amzn-trace-id"); traceID != nil {
req.Header.Set("X-Amzn-Trace-Id", fmt.Sprintf("%v", traceID))
}
req.RemoteAddr = event.RequestContext.Identity.SourceIP
return req, nil
}