Go by Example

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 temporary files and folders with unique names. This avoids choosing a name that another program is already using.

When the directory argument is empty, CreateTemp uses the operating system's temporary folder and returns an open file. Close the file 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, use t.TempDir; Go removes that folder after the test. To replace a file, create the temporary file in the same folder as the target before renaming it. Operating systems differ in how renaming over an existing file works, so check that behavior when it matters. Use permissions that allow only the intended users to read temporary files containing secrets.

Enjoyed this? Get more software craft delivered to your inbox.