Skip to content

Commit

Permalink
feat(enhancement): use request hostname if path is empty or '/' for s…
Browse files Browse the repository at this point in the history
…ave response (#948)
  • Loading branch information
jeevatkm authored Jan 12, 2025
1 parent 433c6ec commit ce2c0be
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 2 deletions.
1 change: 1 addition & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -1791,6 +1791,7 @@ func (c *Client) IsSaveResponse() bool {
// - [Request.SetOutputFileName]
// - Content-Disposition header
// - Request URL using [path.Base]
// - Request URL hostname if path is empty or "/"
//
// It can be overridden at request level, see [Request.SetSaveResponse]
func (c *Client) SetSaveResponse(save bool) *Client {
Expand Down
10 changes: 8 additions & 2 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,8 @@ func AutoParseResponseMiddleware(c *Client, res *Response) (err error) {
return
}

var hostnameReplacer = strings.NewReplacer(":", "_", ".", "_")

// SaveToFileResponseMiddleware method used to write HTTP response body into
// file. The filename is determined in the following order -
// - [Request.SetOutputFileName]
Expand All @@ -557,8 +559,12 @@ func SaveToFileResponseMiddleware(c *Client, res *Response) error {
}
}
if isStringEmpty(file) {
urlPath, _ := url.Parse(res.Request.URL)
file = path.Base(urlPath.Path)
rURL, _ := url.Parse(res.Request.URL)
if isStringEmpty(rURL.Path) || rURL.Path == "/" {
file = hostnameReplacer.Replace(rURL.Host)
} else {
file = path.Base(rURL.Path)
}
}
}

Expand Down
1 change: 1 addition & 0 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,7 @@ func (r *Request) SetOutputFileName(file string) *Request {
// - [Request.SetOutputFileName]
// - Content-Disposition header
// - Request URL using [path.Base]
// - Request URL hostname if path is empty or "/"
//
// It overrides the value set at the client instance level, see [Client.SetSaveResponse]
func (r *Request) SetSaveResponse(save bool) *Request {
Expand Down
7 changes: 7 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1406,6 +1406,13 @@ func TestRequestSaveResponse(t *testing.T) {
assertNil(t, err)
})

t.Run("empty path", func(t *testing.T) {
_, err := c.R().
SetSaveResponse(true).
Get(ts.URL)
assertError(t, err)
})

}

func TestContextInternal(t *testing.T) {
Expand Down

0 comments on commit ce2c0be

Please sign in to comment.