Skip to content

Commit

Permalink
feat(tdhttp): request creation methods/functions init Host field
Browse files Browse the repository at this point in the history
Accepted target can contain scheme://host:port prefix. If it is the case
host:port is used to set Request.Host. If not and the header Host is
present, it is used to set Request.Host.

Signed-off-by: Maxime Soulé <btik-git@scoubidou.com>
  • Loading branch information
maxatome committed Mar 15, 2024
1 parent 7dc6c82 commit 679b2d7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
12 changes: 11 additions & 1 deletion helpers/tdhttp/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,20 +35,30 @@ func newRequest(method string, target string, body io.Reader, headersQueryParams
if err != nil {
return nil, errors.New(color.Bad("target is not a valid path: %s", err))
}
host := u.Host
u.Host = ""
u.Scheme = ""
if len(qp) > 0 {
if u.RawQuery != "" {
u.RawQuery += "&"
}
u.RawQuery += qp.Encode()
target = u.String()
}
target = u.String()

req := httptest.NewRequest(method, target, body)

for k, v := range header {
req.Header[k] = append(req.Header[k], v...)
}

if host == "" {
host = req.Header.Get("Host")
}
if host != "" {
req.Host = host
}

for _, c := range cookies {
req.AddCookie(c)
}
Expand Down
16 changes: 16 additions & 0 deletions helpers/tdhttp/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,22 @@ func TestNewRequest(tt *testing.T) {
t.Cmp(req.URL.String(), "/path?already=true&p1=123&p3=true")
})

t.Run("NewRequest host", func(t *td.T) {
req := tdhttp.NewRequest("GET", "https://pipo.com:123/path", nil)
td.Cmp(t, req.Host, "pipo.com:123")
td.Cmp(t, req.URL, td.String("/path"))

req = tdhttp.NewRequest("GET", "/path", nil, "Host", "pipo.com:456")
td.Cmp(t, req.Host, "pipo.com:456")
td.Cmp(t, req.URL, td.String("/path"))

req = tdhttp.NewRequest(
"GET", "https://pipo.com:123/path", nil,
"Host", "bingo.com:456")
td.Cmp(t, req.Host, "pipo.com:123", "URL wins")
td.Cmp(t, req.URL, td.String("/path"))
})

t.Run("NewRequest panics", func(t *td.T) {
t.CmpPanic(
func() { tdhttp.NewRequest("GET", "/path", nil, "H", "V", true) },
Expand Down

0 comments on commit 679b2d7

Please sign in to comment.