Skip to content

Commit

Permalink
issue #45: rename io.Discard to io.Discarded and improve it for defer…
Browse files Browse the repository at this point in the history
… call
  • Loading branch information
kamilsk committed Feb 20, 2021
1 parent 5f9b80b commit e414a84
Showing 1 changed file with 30 additions and 5 deletions.
35 changes: 30 additions & 5 deletions io/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,36 @@ type (
WriteCloser = io.WriteCloser
)

func Discard(body ReadCloser) Closer {
if _, err := io.Copy(ioutil.Discard, body); err != nil {
return closer(func() error { return err })
}
return body
// Discarded returns the Closer which discards the Reader content before closes it.
//
// import (
// "encoding/json"
// "net/http"
//
// "go.octolab.org/io"
// "go.octolab.org/safe"
// )
//
// func main() {
// resp, err := http.Get(url)
// if err != nil {
// handle(err)
// }
// defer safe.Close(io.Discarded(resp.Body), handle)
//
// var data map[string]interface{}
// if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
// handle(err)
// }
// }
//
func Discarded(body ReadCloser) Closer {
return closer(func() error {
if _, err := io.Copy(ioutil.Discard, body); err != nil {
return err
}
return body.Close()
})
}

// RepeatableReadCloser returns a ReadCloser that can be read an unlimited number of times.
Expand Down

0 comments on commit e414a84

Please sign in to comment.