Skip to content

Commit bc5f024

Browse files
authored
Better empty http response handling (#118)
* client.go: don't call Close() if resp.Body is nil Signed-off-by: Kent R. Spillner <[email protected]> * client.go: support HTTP 204 responses On success, BitBucket's delete APIs return HTTP 204 (No Content). Handle such cases similarly to how we handle expected empty responses on file uploads. Signed-off-by: Kent R. Spillner <[email protected]>
1 parent 330b297 commit bc5f024

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

client.go

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,7 @@ func (c *Client) doRequest(req *http.Request, emptyResponse bool) (interface{},
307307
if err != nil {
308308
return nil, err
309309
}
310-
if emptyResponse {
310+
if emptyResponse || resBody == nil {
311311
return nil, nil
312312
}
313313

@@ -328,24 +328,36 @@ func (c *Client) doRawRequest(req *http.Request, emptyResponse bool) (io.ReadClo
328328
return nil, err
329329
}
330330

331-
if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusCreated) {
331+
if unexpectedHttpStatusCode(resp.StatusCode) {
332332
resp.Body.Close()
333333
return nil, fmt.Errorf(resp.Status)
334334
}
335335

336-
if emptyResponse {
336+
if emptyResponse || resp.StatusCode == http.StatusNoContent {
337337
resp.Body.Close()
338338
return nil, nil
339339
}
340340

341341
if resp.Body == nil {
342-
resp.Body.Close()
343342
return nil, fmt.Errorf("response body is nil")
344343
}
345344

346345
return resp.Body, nil
347346
}
348347

348+
func unexpectedHttpStatusCode(statusCode int) bool {
349+
switch statusCode {
350+
case http.StatusOK:
351+
return false
352+
case http.StatusCreated:
353+
return false
354+
case http.StatusNoContent:
355+
return false
356+
default:
357+
return true
358+
}
359+
}
360+
349361
func (c *Client) requestUrl(template string, args ...interface{}) string {
350362

351363
if len(args) == 1 && args[0] == "" {

0 commit comments

Comments
 (0)