Skip to content

Commit

Permalink
internal requests now use the incoming host to build links, tests added
Browse files Browse the repository at this point in the history
  • Loading branch information
aryan-p03 committed Jan 14, 2025
1 parent 6c6b694 commit 3904b08
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 3 deletions.
5 changes: 4 additions & 1 deletion links/links.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@ type Builder struct {
URL *url.URL
}

func FromHeadersOrDefault(h *http.Header, defaultURL *url.URL) *Builder {
func FromHeadersOrDefault(h *http.Header, r *http.Request, defaultURL *url.URL) *Builder {
host := h.Get("X-Forwarded-Host")
if host == "" {
if r.Host != "" {
defaultURL.Host = r.Host
}
return &Builder{
URL: defaultURL,
}
Expand Down
59 changes: 57 additions & 2 deletions links/links_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
. "github.com/smartystreets/goconvey/convey"
)

func Test_FromHeadersOrDefault(t *testing.T) {
func Test_FromHeadersOrDefault_With_Forwarded_Headers(t *testing.T) {

Convey("Given a list of test cases", t, func() {
tests := []struct {
Expand Down Expand Up @@ -184,7 +184,7 @@ func Test_FromHeadersOrDefault(t *testing.T) {
}

du.JoinPath()
builder := FromHeadersOrDefault(&h, du)
builder := FromHeadersOrDefault(&h, &http.Request{}, du)
So(builder, ShouldNotBeNil)
So(builder.URL, ShouldNotBeNil)
So(builder.URL.String(), ShouldEqual, tt.want)
Expand All @@ -195,6 +195,61 @@ func Test_FromHeadersOrDefault(t *testing.T) {

}

func Test_FromHeadersOrDefault_Without_Forwarded_Headers(t *testing.T) {

Convey("Given a list of test cases", t, func() {
tests := []struct {
incomingRequestHost string
defaultURL string
want string
}{
// Without incoming request host
{
"",
"http://localhost:8080/",
"http://localhost:8080/",
},
// With incoming request host and no port
{
"localhost",
"http://localhost:8080/",
"http://localhost/",
},
// With incoming request host and different port
{
"localhost:6789",
"http://localhost:8080/",
"http://localhost:6789/",
},
{
"10.30.100.123:4567",
"http://localhost:8080/",
"http://10.30.100.123:4567/",
},
// With incoming request host and default URL with path
{
"localhost",
"http://localhost:8080/some/path",
"http://localhost/some/path",
},
}

for _, tt := range tests {
du, err := url.Parse(tt.defaultURL)
So(err, ShouldBeNil)

incomingRequest := &http.Request{Host: tt.incomingRequestHost}

builder := FromHeadersOrDefault(&http.Header{}, incomingRequest, du)
So(builder, ShouldNotBeNil)
So(builder.URL, ShouldNotBeNil)
So(builder.URL.String(), ShouldEqual, tt.want)

}

})
}

func TestBuilder_BuildLink(t *testing.T) {

Convey("Given a list of test cases", t, func() {
Expand Down

0 comments on commit 3904b08

Please sign in to comment.