This repository has been archived by the owner on Jan 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
server.go
176 lines (150 loc) · 4.54 KB
/
server.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
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
//
// Copyright 2017 Alsanium, SAS. or its affiliates. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package apigatewayproxy
import (
"encoding/base64"
"encoding/json"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"github.com/eawsy/aws-lambda-go-core/service/lambda/runtime"
"github.com/eawsy/aws-lambda-go-event/service/lambda/runtime/event/apigatewayproxyevt"
)
// Handler responds to a Lambda function invocation.
type Handler func(json.RawMessage, *runtime.Context) (*Response, error)
// Server defines parameters for handling requests coming from Amazon API
// Gateway. The zero value for Server is not a valid configuration, use New
// instead.
type Server struct {
pt string
ts map[string]bool
}
// New returns an initialized server to handle requests from Amazon API Gateway.
// The given media types slice may be nil, if Amazon API Gateway Binary support
// is not enabled. Otherwise, it should be an array of supported media types as
// configured in Amazon API Gateway.
func New(ln net.Listener, ts []string) *Server {
s := &Server{"http://" + ln.Addr().String(), make(map[string]bool)}
for _, t := range ts {
s.ts[t] = true
}
return s
}
// Response defines parameters for a well formed response AWS Lambda should
// return to Amazon API Gateway.
type Response struct {
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
IsBase64Encoded bool `json:"isBase64Encoded"`
}
func newClient() *http.Client {
return &http.Client{
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
// Handle responds to an AWS Lambda proxy function invocation via Amazon API
// Gateway.
// It transforms the Amazon API Gateway Proxy event to a standard HTTP request
// suitable for the Go net/http package. Then, it submits the data to the
// network listener so that it can be consumed by HTTP handler. Finally, it
// waits for the network listener to return response from handler and transmits
// it back to Amazon API Gateway.
func (s *Server) Handle(evt json.RawMessage, ctx *runtime.Context) (gwres *Response, dummy error) {
gwreq := new(apigatewayproxyevt.Event)
gwres = &Response{StatusCode: http.StatusInternalServerError}
if err := json.Unmarshal(evt, &gwreq); err != nil {
log.Println(err)
return
}
u, err := url.Parse(gwreq.Path)
if err != nil {
log.Println(err)
return
}
q := u.Query()
for k, v := range gwreq.QueryStringParameters {
q.Set(k, v)
}
u.RawQuery = q.Encode()
dec := gwreq.Body
if gwreq.IsBase64Encoded {
data, err := base64.StdEncoding.DecodeString(dec)
if err != nil {
log.Println(err)
return
}
dec = string(data)
}
req, err := http.NewRequest(gwreq.HTTPMethod, s.pt+u.String(), strings.NewReader(dec))
if err != nil {
log.Println(err)
return
}
gwreq.Body = "... truncated"
for k, v := range gwreq.Headers {
req.Header.Set(k, v)
}
if len(req.Header.Get("X-Forwarded-For")) == 0 {
req.Header.Set("X-Forwarded-For", gwreq.RequestContext.Identity.SourceIP)
}
hbody, err := json.Marshal(gwreq)
if err != nil {
log.Println(err)
return
}
req.Header.Set("X-ApiGatewayProxy-Event", string(hbody))
hctx, err := json.Marshal(ctx)
if err != nil {
log.Println(err)
return
}
req.Header.Set("X-ApiGatewayProxy-Context", string(hctx))
req.Host = gwreq.Headers["Host"]
res, err := newClient().Do(req)
if err != nil {
log.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Println(err)
return
}
ct := res.Header.Get("Content-Type")
if ct == "" {
ct = http.DetectContentType(body)
res.Header.Set("Content-Type", ct)
}
if _, ok := s.ts[ct]; ok {
gwres.Body = base64.StdEncoding.EncodeToString(body)
gwres.IsBase64Encoded = true
} else {
gwres.Body = string(body)
}
gwres.Headers = make(map[string]string)
for k := range res.Header {
gwres.Headers[k] = res.Header.Get(k)
}
gwres.StatusCode = res.StatusCode
return
}