github.com/nikandfor/tlog@v0.21.5-0.20231108111739-3ef89426a96d/tlio/closers.go (about)

     1  package tlio
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/nikandfor/errors"
     7  )
     8  
     9  type (
    10  	WrappedCloser struct {
    11  		io.Closer
    12  		Msg  string
    13  		Args []interface{}
    14  	}
    15  
    16  	CloserFunc func() error
    17  )
    18  
    19  func Close(f interface{}) error {
    20  	c, ok := f.(io.Closer)
    21  	if !ok {
    22  		return nil
    23  	}
    24  
    25  	return c.Close()
    26  }
    27  
    28  func CloseWrap(f interface{}, name string, errp *error) { //nolint:gocritic
    29  	e := Close(f)
    30  	if *errp == nil {
    31  		*errp = errors.Wrap(e, "close %v", name)
    32  	}
    33  }
    34  
    35  func WrapCloser(c io.Closer, msg string, args ...interface{}) io.Closer {
    36  	return WrappedCloser{
    37  		Closer: c,
    38  		Msg:    msg,
    39  		Args:   args,
    40  	}
    41  }
    42  
    43  func WrapCloserFunc(cf func() error, msg string, args ...interface{}) io.Closer {
    44  	return WrappedCloser{
    45  		Closer: CloserFunc(cf),
    46  		Msg:    msg,
    47  		Args:   args,
    48  	}
    49  }
    50  
    51  func (c WrappedCloser) Close() (err error) {
    52  	err = c.Closer.Close()
    53  	if err != nil {
    54  		return errors.WrapDepth(err, 1, c.Msg, c.Args...)
    55  	}
    56  
    57  	return nil
    58  }
    59  
    60  func (c CloserFunc) Close() error { return c() }