Skip to content

Commit 290b208

Browse files
authored
Merge pull request aws#339 from SAPessi/develop
Added Forward headers similar to API Gateway's
2 parents 2844be1 + c9bdb4b commit 290b208

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

router/event.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/json"
55
"io/ioutil"
66
"net/http"
7+
"strings"
78

89
"github.com/gorilla/mux"
910
)
@@ -69,6 +70,17 @@ func NewEvent(req *http.Request, isBase64Encoded bool) (*Event, error) {
6970
}
7071
}
7172

73+
// add the forwarded headers we expect to see from an API Gateway request
74+
if _, ok := headers["Host"]; !ok {
75+
host := req.Host
76+
if strings.Contains(host, ":") {
77+
host = host[:strings.Index(host, ":")]
78+
}
79+
headers["Host"] = host
80+
}
81+
headers["X-Forwarded-Proto"] = req.URL.Scheme
82+
headers["X-Forwarded-Port"] = req.URL.Port()
83+
7284
query := map[string]string{}
7385
for name, values := range req.URL.Query() {
7486
for _, value := range values {

router/event_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,40 @@ var _ = Describe("Event", func() {
8181
r.Router().ServeHTTP(rec, req)
8282
})
8383
})
84+
85+
Context("Includes forwarded headers", func() {
86+
req, _ := http.NewRequest("GET", "http://localhost:3000/get", new(bytes.Buffer))
87+
88+
It("Includes Host header", func() {
89+
r.AddFunction(function, func(w http.ResponseWriter, e *Event) {
90+
hostHeader, ok := e.Headers["Host"]
91+
Expect(ok).To(BeTrue())
92+
Expect(hostHeader).To(BeIdenticalTo("localhost"))
93+
})
94+
rec := httptest.NewRecorder()
95+
r.Router().ServeHTTP(rec, req)
96+
})
97+
98+
It("Includes X-Forwarded-Proto header", func() {
99+
r.AddFunction(function, func(w http.ResponseWriter, e *Event) {
100+
hostHeader, ok := e.Headers["X-Forwarded-Proto"]
101+
Expect(ok).To(BeTrue())
102+
Expect(hostHeader).To(BeIdenticalTo("http"))
103+
})
104+
rec := httptest.NewRecorder()
105+
r.Router().ServeHTTP(rec, req)
106+
})
107+
108+
It("Includes X-Forwarded-Port header", func() {
109+
r.AddFunction(function, func(w http.ResponseWriter, e *Event) {
110+
hostHeader, ok := e.Headers["X-Forwarded-Port"]
111+
Expect(ok).To(BeTrue())
112+
Expect(hostHeader).To(BeIdenticalTo("3000"))
113+
})
114+
rec := httptest.NewRecorder()
115+
r.Router().ServeHTTP(rec, req)
116+
})
117+
})
84118
})
85119

86120
Context("with no parameters on the route", func() {

0 commit comments

Comments
 (0)