Created
November 23, 2024 15:06
-
-
Save imjasonh/3d274880cc87006d7a9d255ae1514099 to your computer and use it in GitHub Desktop.
Auto cleaning temp dirs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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