close.go (795B)
1 package iotools 2 3 import "io" 4 5 // CloserFunc is a function signature which allows 6 // a function to implement the io.Closer type. 7 type CloserFunc func() error 8 9 func (c CloserFunc) Close() error { 10 return c() 11 } 12 13 func CloserCallback(c io.Closer, cb func()) io.Closer { 14 return CloserFunc(func() error { 15 defer cb() 16 return c.Close() 17 }) 18 } 19 20 func CloserAfterCallback(c io.Closer, cb func()) io.Closer { 21 return CloserFunc(func() (err error) { 22 defer func() { err = c.Close() }() 23 cb() 24 return 25 }) 26 } 27 28 // CloseOnce wraps an io.Closer to ensure it only performs the close logic once. 29 func CloseOnce(c io.Closer) io.Closer { 30 return CloserFunc(func() error { 31 if c == nil { 32 // already run. 33 return nil 34 } 35 36 // Acquire. 37 cptr := c 38 c = nil 39 40 // Call the closer. 41 return cptr.Close() 42 }) 43 }