From c340fb9a0f1f7c025da5ffa2d1a7389a4eabaae2 Mon Sep 17 00:00:00 2001 From: "Santiago M. Mola" Date: Mon, 6 Feb 2017 17:42:51 +0100 Subject: doc: add package documentation for utils/ioutil, fix #246. --- utils/ioutil/common.go | 1 + 1 file changed, 1 insertion(+) (limited to 'utils/ioutil') diff --git a/utils/ioutil/common.go b/utils/ioutil/common.go index a847abd..12ea9eb 100644 --- a/utils/ioutil/common.go +++ b/utils/ioutil/common.go @@ -1,3 +1,4 @@ +// Package ioutil implements some I/O utility functions. package ioutil import ( -- cgit From 70eff0d7bd1f69856f8028c2487576085a54a42c Mon Sep 17 00:00:00 2001 From: "Santiago M. Mola" Date: Mon, 6 Feb 2017 17:55:14 +0100 Subject: doc: improve ioutil.CheckClose doc and example, fix #246. * Use a proper executable example, instead of one in the comment. * Improve wording of CheckClose godoc. --- utils/ioutil/common.go | 17 +++-------------- utils/ioutil/common_test.go | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 14 deletions(-) (limited to 'utils/ioutil') diff --git a/utils/ioutil/common.go b/utils/ioutil/common.go index 12ea9eb..73cc9c3 100644 --- a/utils/ioutil/common.go +++ b/utils/ioutil/common.go @@ -64,20 +64,9 @@ func WriteNopCloser(w io.Writer) io.WriteCloser { return writeNopCloser{w} } -// CheckClose is used with defer to close the given io.Closer and check its -// returned error value. If Close returns an error and the given *error -// is not nil, *error is set to the error returned by Close. -// -// CheckClose is typically used with named return values like so: -// -// func do(obj *Object) (err error) { -// w, err := obj.Writer() -// if err != nil { -// return nil -// } -// defer CheckClose(w, &err) -// // work with w -// } +// CheckClose calls Close on the given io.Closer. If the given *error points to +// nil, it will be assigned the error returned by Close. Otherwise, any error +// returned by Close will be ignored. CheckClose is usually called with defer. func CheckClose(c io.Closer, err *error) { if cerr := c.Close(); cerr != nil && *err == nil { *err = cerr diff --git a/utils/ioutil/common_test.go b/utils/ioutil/common_test.go index f5017f7..2d6ef80 100644 --- a/utils/ioutil/common_test.go +++ b/utils/ioutil/common_test.go @@ -3,6 +3,7 @@ package ioutil import ( "bytes" "io/ioutil" + "strings" "testing" . "gopkg.in/check.v1" @@ -53,3 +54,25 @@ func (s *CommonSuite) TestNewReadCloser(c *C) { c.Assert(r.Close(), IsNil) c.Assert(closer.called, Equals, 1) } + +func ExampleCheckClose() { + // CheckClose is commonly used with named return values + f := func() (err error) { + // Get a io.ReadCloser + r := ioutil.NopCloser(strings.NewReader("foo")) + + // defer CheckClose call with an io.Closer and pointer to error + defer CheckClose(r, &err) + + // ... work with r ... + + // if err is not nil, CheckClose will assign any close errors to it + return err + + } + + err := f() + if err != nil { + panic(err) + } +} -- cgit