-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathhttp_exhaust.go
39 lines (32 loc) · 983 Bytes
/
http_exhaust.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Copyright (c) Efficient Go Authors
// Licensed under the Apache License 2.0.
package leak
import (
"net/http"
"github.com/efficientgo/core/errcapture"
"github.com/efficientgo/core/errors"
)
// Examples of code which is leaking resources, because of not exhausted readers.
// Read more in "Efficient Go"; Example 11-10.
func handleResp_Wrong(resp *http.Response) error {
if resp.StatusCode != http.StatusOK {
return errors.Newf("got non-200 response; code: %v", resp.StatusCode)
}
return nil
}
func handleResp_StillWrong(resp *http.Response) error {
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return errors.Newf("got non-200 response; code: %v", resp.StatusCode)
}
return nil
}
func handleResp_Better(resp *http.Response) (err error) {
defer errcapture.ExhaustClose(&err, resp.Body, "close")
if resp.StatusCode != http.StatusOK {
return errors.Newf("got non-200 response; code: %v", resp.StatusCode)
}
return nil
}