Skip to content

Instantly share code, notes, and snippets.

@hxzhouh

hxzhouh/main.go Secret

Created December 17, 2024 09:06
Show Gist options
  • Select an option

  • Save hxzhouh/5bb1d55259dcb4dab87b37beaef9bea2 to your computer and use it in GitHub Desktop.

Select an option

Save hxzhouh/5bb1d55259dcb4dab87b37beaef9bea2 to your computer and use it in GitHub Desktop.
close file by AddCleanup
func NewFileResource(filename string) (*os.File, error) {
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
return nil, err
}
runtime.AddCleanup(file, func(f *os.File) {
fmt.Println("close f")
_ = f.Close()
}, file)
return file, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment