Skip to content

Commit

Permalink
Addressing SetScheme option side effects on schemaless Host URL #407
Browse files Browse the repository at this point in the history
  • Loading branch information
jeevatkm committed Sep 14, 2021
1 parent 79cc4d4 commit 48a5f15
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 7 deletions.
2 changes: 1 addition & 1 deletion client.go
Expand Up @@ -758,7 +758,7 @@ func (c *Client) SetTransport(transport http.RoundTripper) *Client {
// client.SetScheme("http")
func (c *Client) SetScheme(scheme string) *Client {
if !IsStringEmpty(scheme) {
c.scheme = scheme
c.scheme = strings.TrimSpace(scheme)
}
return c
}
Expand Down
43 changes: 43 additions & 0 deletions client_test.go
Expand Up @@ -744,3 +744,46 @@ func TestResponseError(t *testing.T) {
assertNotNil(t, re.Unwrap())
assertEqual(t, err.Error(), re.Error())
}

func TestHostURLForGH318AndGH407(t *testing.T) {
ts := createPostServer(t)
defer ts.Close()

targetURL, _ := url.Parse(ts.URL)
t.Log("ts.URL:", ts.URL)
t.Log("targetURL.Host:", targetURL.Host)
// Sample output
// ts.URL: http://127.0.0.1:55967
// targetURL.Host: 127.0.0.1:55967

// Unable use the local http test server for this
// use case testing
//
// using `targetURL.Host` value or test case yield to ERROR
// "parse "127.0.0.1:55967": first path segment in URL cannot contain colon"

// test the functionality with httpbin.org locally
// will figure out later

c := dc()
// c.SetScheme("http")
// c.SetHostURL(targetURL.Host + "/")

// t.Log("with leading `/`")
// resp, err := c.R().Post("/login")
// assertNil(t, err)
// assertNotNil(t, resp)

// t.Log("\nwithout leading `/`")
// resp, err = c.R().Post("login")
// assertNil(t, err)
// assertNotNil(t, resp)

t.Log("with leading `/` on request & with trailing `/` on host url")
c.SetHostURL(ts.URL + "/")
resp, err := c.R().
SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
Post("/login")
assertNil(t, err)
assertNotNil(t, resp)
}
11 changes: 5 additions & 6 deletions middleware.go
Expand Up @@ -60,6 +60,11 @@ func parseRequestURL(c *Client, r *Request) error {
}
}

// GH #407 && #318
if reqURL.Scheme == "" && len(c.scheme) > 0 {
reqURL.Scheme = c.scheme
}

// Adding Query Param
query := make(url.Values)
for k, v := range c.QueryParam {
Expand Down Expand Up @@ -191,12 +196,6 @@ func createHTTPRequest(c *Client, r *Request) (err error) {
r.RawRequest.AddCookie(cookie)
}

// it's for non-http scheme option
if r.RawRequest.URL != nil && r.RawRequest.URL.Scheme == "" {
r.RawRequest.URL.Scheme = c.scheme
r.RawRequest.URL.Host = r.URL
}

// Enable trace
if c.trace || r.trace {
r.clientTrace = &clientTrace{}
Expand Down

0 comments on commit 48a5f15

Please sign in to comment.