Skip to content

Instantly share code, notes, and snippets.

@imjasonh
Created November 23, 2024 15:06
Show Gist options
  • Save imjasonh/3d274880cc87006d7a9d255ae1514099 to your computer and use it in GitHub Desktop.
Save imjasonh/3d274880cc87006d7a9d255ae1514099 to your computer and use it in GitHub Desktop.
Auto cleaning temp dirs
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"os"
"runtime"
"time"
)
func main() {
foo()
foo()
runtime.GC()
time.Sleep(time.Second)
}
func foo() {
var tmp string
defer TempDir(&tmp)()
fmt.Println("foo temp is", tmp)
bar()
}
func bar() {
var tmp string
defer TempDir(&tmp)()
fmt.Println("bar temp is", tmp)
}
func TempDir(s *string) func() {
d, _ := os.MkdirTemp("", "")
*s = d
x := "."
f := func() { x = "" }
runtime.SetFinalizer(&x, func(*string) {
os.RemoveAll(d)
fmt.Println("deleted", d)
})
return f
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment