github.com/Schaudge/grailbase@v0.0.0-20240223061707-44c758a471c0/fileio/close.go (about) 1 package fileio 2 3 import ( 4 "fmt" 5 "io" 6 7 "github.com/Schaudge/grailbase/errors" 8 ) 9 10 type named interface { 11 // Name returns the path name. 12 Name() string 13 } 14 15 // CloseAndReport returns a defer-able helper that calls f.Close and reports errors, if any, 16 // to *err. Pass your function's named return error. Example usage: 17 // 18 // func processFile(filename string) (_ int, err error) { 19 // f, err := os.Open(filename) 20 // if err != nil { ... } 21 // defer fileio.CloseAndReport(f, &err) 22 // ... 23 // } 24 // 25 // If your function returns with an error, any f.Close error will be chained appropriately. 26 // 27 // Deprecated: Use errors.CleanUp directly. 28 func CloseAndReport(f io.Closer, err *error) { 29 errors.CleanUp(f.Close, err) 30 } 31 32 // MustClose is a defer-able function that calls f.Close and panics on error. 33 // 34 // Example: 35 // f, err := os.Open(filename) 36 // if err != nil { panic(err) } 37 // defer fileio.MustClose(f) 38 // ... 39 func MustClose(f io.Closer) { 40 if err := f.Close(); err != nil { 41 if n, ok := f.(named); ok { 42 panic(fmt.Sprintf("close %s: %v", n.Name(), err)) 43 } 44 panic(err) 45 } 46 }