-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (75 loc) · 2.28 KB
/
main.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
package apiggo
import (
"encoding/base64"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"github.com/aws/aws-lambda-go/events"
)
// Handler turns an APIGatewayProxyRequest into a standard http.Request
func Handler(handler http.Handler, host string, proxyRequest events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
//Check if the APIGatewayProxyRequest.Body is a base64 encoded string
// If it is, decode it
var body string
decodedBody, err := base64.StdEncoding.DecodeString(proxyRequest.Body)
if err != nil {
body = proxyRequest.Body
} else {
body = string(decodedBody)
}
// Create a new *http.Request and *httptest.ResponseRecorder
r := httptest.NewRequest(proxyRequest.HTTPMethod, proxyRequest.Path, strings.NewReader(body))
w := httptest.NewRecorder()
// Set the host to whatever your APIG base path is
r.Host = host
// Add the APIGatewayProxyRequest headers to the *http.Request
for key, value := range proxyRequest.Headers {
r.Header.Add(key, value)
}
// Create a x-url-formencoded string from QueryStringParameters
var queryString string
for key, value := range proxyRequest.QueryStringParameters {
queryString = fmt.Sprintf("%s%s=%s&", queryString, key, value)
}
queryString = strings.TrimSuffix(queryString, "&")
// Ensure all paths have a trailing slash for consistency
path := proxyRequest.Path
if !strings.HasSuffix(path, "/") {
path = path + "/"
}
// Create a new url.URL
rURL := url.URL{
Scheme: "https",
Opaque: "",
User: nil,
Host: host,
Path: path,
RawPath: path,
ForceQuery: false,
RawQuery: queryString,
Fragment: "",
}
r.URL = &rURL
//Start serving
handler.ServeHTTP(w, r)
// Add the response headers to a map that can be used in the APIGatewayProxyResponse
// It is important to do this AFTER receiving requests
respHeaders := map[string]string{}
for key, value := range w.Header() {
respHeaders[key] = strings.Join(value, "")
}
isBase64Encoded := true
_, err = base64.StdEncoding.DecodeString(w.Body.String())
if err != nil {
isBase64Encoded = false
}
proxyResp := events.APIGatewayProxyResponse{
Body: w.Body.String(),
Headers: respHeaders,
StatusCode: w.Code,
IsBase64Encoded: isBase64Encoded,
}
return proxyResp, nil
}