-
Notifications
You must be signed in to change notification settings - Fork 136
/
request.go
92 lines (79 loc) · 2.2 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
89
90
91
92
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"bytes"
"encoding/base64"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
"github.com/aws/aws-lambda-go/events"
)
// 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 request
const DefaultServerAddress = "https://aws-serverless-go-api.com"
type RequestAccessor struct {
stripBasePath string
}
func (r *RequestAccessor) ProxyEventToHTTPRequest(req events.ALBTargetGroupRequest) (*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
}
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])
}
for hk, hvs := range req.MultiValueHeaders {
for _, hv := range hvs {
httpRequest.Header.Add(hk, hv)
}
}
return httpRequest, nil
}