fix crash when req is called with no body

This commit is contained in:
Ringo Hoffmann 2021-11-08 23:10:07 +01:00 committed by Christoph Polcin
parent adba8dc051
commit 3f8721cd4b

View File

@ -13,27 +13,26 @@ func (c *Client) req(method, path string, body io.Reader, intercept func(*http.R
var r *http.Request var r *http.Request
var retryBuf io.Reader var retryBuf io.Reader
// If the authorization fails, we will need to restart reading if body != nil {
// from the passed body stream. // If the authorization fails, we will need to restart reading
// When body is seekable, use seek to reset the streams // from the passed body stream.
// cursor to the start. // When body is seekable, use seek to reset the streams
// Otherwise, copy the stream into a buffer while uploading // cursor to the start.
// and use the buffers content on retry. // Otherwise, copy the stream into a buffer while uploading
if sk, ok := body.(io.Seeker); ok { // and use the buffers content on retry.
if _, err = sk.Seek(0, io.SeekStart); err != nil { if sk, ok := body.(io.Seeker); ok {
return if _, err = sk.Seek(0, io.SeekStart); err != nil {
return
}
retryBuf = body
} else {
buff := &bytes.Buffer{}
retryBuf = buff
body = io.TeeReader(body, buff)
} }
retryBuf = body
} else {
buff := &bytes.Buffer{}
retryBuf = buff
body = io.TeeReader(body, buff)
}
if body == nil {
r, err = http.NewRequest(method, PathEscape(Join(c.root, path)), nil)
} else {
r, err = http.NewRequest(method, PathEscape(Join(c.root, path)), body) r, err = http.NewRequest(method, PathEscape(Join(c.root, path)), body)
} else {
r, err = http.NewRequest(method, PathEscape(Join(c.root, path)), nil)
} }
if err != nil { if err != nil {
@ -82,12 +81,9 @@ func (c *Client) req(method, path string, body io.Reader, intercept func(*http.R
return rs, newPathError("Authorize", c.root, rs.StatusCode) return rs, newPathError("Authorize", c.root, rs.StatusCode)
} }
if body == nil { // retryBuf will be nil if body was nil initially so no check
return c.req(method, path, nil, intercept) // for body == nil is required here.
} else { return c.req(method, path, retryBuf, intercept)
return c.req(method, path, retryBuf, intercept)
}
} else if rs.StatusCode == 401 { } else if rs.StatusCode == 401 {
return rs, newPathError("Authorize", c.root, rs.StatusCode) return rs, newPathError("Authorize", c.root, rs.StatusCode)
} }