Temporary Files and Directories
os.CreateTemp and os.MkdirTemp for creating temporary files and directories, deferred cleanup, and t.TempDir in tests.
os.CreateTemp and os.MkdirTemp create uniquely named temporary paths. They avoid the collisions that can occur when a program invents a filename itself.
CreateTemp returns an open file in the system temporary directory when the directory argument is empty. Close and remove it when finished.
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.CreateTemp("", "example-")
if err != nil {
panic(err)
}
defer os.Remove(file.Name())
defer file.Close()
if _, err := file.WriteString("temporary data"); err != nil {
panic(err)
}
fmt.Println(file.Name())
}In production
In tests, prefer t.TempDir, which the test runner removes after the test. For a rename-based replacement, create the temporary file in the target directory so both paths are on the same filesystem. Rename atomicity and overwrite behavior are platform-specific, so check those guarantees when they matter. Use restrictive permissions for temporary data that contains secrets.