Temporary files

suggest change

Programs often need a file or a directory for a short time: a download that must be checked before it's used, a large intermediate result that doesn't fit in memory, a scratch directory for running an external tool, the new version of a file that will replace the old one, or test fixtures.

Package os has everything you need:

Go doesn't delete temporary files for you (except in tests). Removing them is your job.

ioutil.TempFile and ioutil.TempDir from older code are deprecated. They are the same functions as os.CreateTemp and os.MkdirTemp, so just switch to the os versions.

Where temporary files go: os.TempDir

package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("temp dir:", os.TempDir())
}
temp dir: /tmp

On Windows it prints something like C:\Users\kjk\AppData\Local\Temp.

os.TempDir doesn't create or check anything; it only reads the environment:

So a user can move temporary files to another disk by setting a variable:

$ TMPDIR=/var/tmp ./app
temp dir: /var/tmp

You rarely need to call os.TempDir yourself: passing "" as the directory to os.CreateTemp or os.MkdirTemp means "use os.TempDir()".

Create a temporary file: os.CreateTemp

os.CreateTemp creates a new file, opens it for reading and writing and returns an *os.File. f.Name() is the full path of the file.

package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
)

func main() {
	// "" means: create the file in os.TempDir()
	f, err := os.CreateTemp("", "report-*.txt")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	// defers run in reverse order: Close first, then Remove
	defer os.Remove(f.Name())
	defer f.Close()

	fmt.Println("dir: ", filepath.Dir(f.Name()) == filepath.Clean(os.TempDir()))
	fmt.Println("name:", filepath.Base(f.Name()))

	if _, err := f.WriteString("line 1\nline 2\n"); err != nil {
		fmt.Println("error:", err)
		return
	}

	// the file offset is now at the end; rewind to read what we wrote
	if _, err := f.Seek(0, io.SeekStart); err != nil {
		fmt.Println("error:", err)
		return
	}
	data, err := io.ReadAll(f)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("read back: %q\n", data)
}
dir:  true
name: report-2493853698.txt
read back: "line 1\nline 2\n"

Things to notice:

Name patterns

The second argument is a pattern for the file name. The random string replaces the last * in the pattern. If there's no *, the random string is added at the end.

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	dir, err := os.MkdirTemp("", "patterns-")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.RemoveAll(dir)

	patterns := []string{"", "upload-", "upload-*.jpg", "*.json", "sub/x-*"}
	for _, p := range patterns {
		f, err := os.CreateTemp(dir, p)
		if err != nil {
			fmt.Printf("%-14q error: %v\n", p, err)
			continue
		}
		fmt.Printf("%-14q %s\n", p, filepath.Base(f.Name()))
		f.Close()
	}
}
""             4177114276
"upload-"      upload-2980479477
"upload-*.jpg" upload-2454909694.jpg
"*.json"       2827211667.json
"sub/x-*"      error: createtemp sub/x-*: pattern contains path separator

Tips for patterns:

The directory passed as dir must exist. CreateTemp doesn't create it.

Create a temporary directory: os.MkdirTemp

When you need more than one file, create a temporary directory and put everything inside. Cleanup is a single os.RemoveAll.

package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
)

func main() {
	dir, err := os.MkdirTemp("", "build-*")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.RemoveAll(dir) // removes the directory and everything in it

	fmt.Println("created:", filepath.Base(dir))

	files := map[string]string{
		"go.mod":         "module example\n",
		"main.go":        "package main\n",
		"assets/app.css": "body {}\n",
	}
	for name, content := range files {
		path := filepath.Join(dir, name)
		if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
			fmt.Println("error:", err)
			return
		}
		if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
			fmt.Println("error:", err)
			return
		}
	}

	filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		rel, _ := filepath.Rel(dir, path)
		fmt.Println(" ", filepath.ToSlash(rel))
		return nil
	})
}
created: build-3727889812
  .
  assets
  assets/app.css
  go.mod
  main.go

os.MkdirTemp uses the same pattern rules as os.CreateTemp. os.RemoveAll removes the directory with everything in it and returns nil if it doesn't exist, so it's safe to call in a defer even if the code already removed it. See Directory operations for more about working with directories.

A temporary directory is also the cleanest way to give an external program its own workspace. Set cmd.Dir of an exec.Cmd to the directory, let the program write whatever it wants there, then remove it all.

Permissions

Temporary files often hold private data: uploads, decrypted content, credentials. os.CreateTemp creates files with mode 0600 and os.MkdirTemp creates directories with mode 0700, so on Unix only the owner can read them:

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.CreateTemp("", "secret-*")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.Remove(f.Name())
	defer f.Close()

	dir, err := os.MkdirTemp("", "work-*")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.RemoveAll(dir)

	fi, _ := f.Stat()
	fmt.Println("file:", fi.Mode())
	di, _ := os.Stat(dir)
	fmt.Println("dir: ", di.Mode())
}

Output on Linux:

file: -rw-------
dir:  drwx------

On Windows Go only maps the read-only attribute to Unix permission bits, so it prints -rw-rw-rw- and drwxrwxrwx. Access on Windows is controlled by ACLs, and the user's temp directory is already private to the user.

If the file ends up somewhere other users must read it (for example a file you rename into place, as in the next section), change the mode with os.Chmod or f.Chmod.

Never create temporary files with a fixed or predictable name like /tmp/myapp.tmp. On a shared machine another user can create that file (or a symbolic link with that name) first. Your program then writes into a file the attacker controls. The random name plus O_EXCL used by os.CreateTemp prevents this.

Atomic file replacement

Writing a file in place isn't safe: if the program crashes or the disk fills up in the middle, the file is left half written. The standard fix is to write a temporary file and then rename it over the original. On Unix rename is atomic, and on Windows os.Rename replaces the destination in one step too. Readers see either the old file or the new one.

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

// writeFileAtomic writes data to path so that readers see either the
// old content or the new content, never a partially written file.
func writeFileAtomic(path string, data []byte, perm os.FileMode) (err error) {
	// the temp file must be in the same directory (same file system)
	// as the destination, otherwise os.Rename fails
	f, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+"-*.tmp")
	if err != nil {
		return err
	}
	tmpName := f.Name()
	defer func() {
		if err != nil {
			f.Close()
			os.Remove(tmpName) // don't leave garbage behind on failure
		}
	}()

	if _, err = f.Write(data); err != nil {
		return err
	}
	// flush to disk before rename so a crash can't leave an empty file
	if err = f.Sync(); err != nil {
		return err
	}
	if err = f.Close(); err != nil {
		return err
	}
	// CreateTemp uses 0600; give the final file the permissions we want
	if err = os.Chmod(tmpName, perm); err != nil {
		return err
	}
	return os.Rename(tmpName, path)
}

func main() {
	dir, err := os.MkdirTemp("", "atomic-*")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.RemoveAll(dir)

	path := filepath.Join(dir, "state.json")
	for i := 1; i <= 3; i++ {
		data := fmt.Appendf(nil, "{\"version\": %d}\n", i)
		if err := writeFileAtomic(path, data, 0o644); err != nil {
			fmt.Println("error:", err)
			return
		}
	}

	data, _ := os.ReadFile(path)
	fmt.Print(string(data))

	entries, _ := os.ReadDir(dir)
	for _, e := range entries {
		fmt.Println("file in dir:", e.Name())
	}
}
{"version": 3}
file in dir: state.json

The details matter:

The Configuration files article uses the same technique to save settings.

Spilling data to disk

A temporary file is a good place to store data that is too large to keep in memory or that you need to read more than once: you can validate it, hash it, then process it. A typical example is a file upload or a download of unknown size:

package main

import (
	"crypto/sha256"
	"fmt"
	"io"
	"os"
	"strings"
)

// saveUpload copies an upload of unknown size to a temp file, so it can
// be validated before anything else sees it. The caller owns the
// returned file and must close and remove it.
func saveUpload(r io.Reader, maxSize int64) (*os.File, int64, error) {
	f, err := os.CreateTemp("", "upload-*")
	if err != nil {
		return nil, 0, err
	}
	cleanup := func() {
		f.Close()
		os.Remove(f.Name())
	}

	// read one byte more than allowed to detect oversized input
	n, err := io.Copy(f, io.LimitReader(r, maxSize+1))
	if err != nil {
		cleanup()
		return nil, 0, err
	}
	if n > maxSize {
		cleanup()
		return nil, 0, fmt.Errorf("upload too large: more than %d bytes", maxSize)
	}
	if _, err := f.Seek(0, io.SeekStart); err != nil {
		cleanup()
		return nil, 0, err
	}
	return f, n, nil
}

func main() {
	body := strings.NewReader(strings.Repeat("hello temp file\n", 1000))
	f, n, err := saveUpload(body, 1<<20)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.Remove(f.Name())
	defer f.Close()

	// the file can now be read as many times as needed
	h := sha256.New()
	io.Copy(h, f)
	fmt.Printf("size: %d\nsha256: %x\n", n, h.Sum(nil)[:8])

	_, _, err = saveUpload(strings.NewReader(strings.Repeat("x", 2000)), 1000)
	fmt.Println("error:", err)
}
size: 16000
sha256: 0f88081f4326fcd5
error: upload too large: more than 1000 bytes

The function returns an open file. Ownership of the file moves to the caller, who must close and remove it. On every error path the function cleans up after itself, so a failed upload doesn't leak a file. For receiving uploads in an HTTP server, see File uploads. Note that mime/multipart already stores large uploaded files in temporary files for you; call r.MultipartForm.RemoveAll() when done.

Removing temporary files

Here's what you need to know about cleanup.

Close before removing on Windows

On Windows you can't delete a file that is open:

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.CreateTemp("", "open-*")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	f.WriteString("data")

	// try to remove while the file is still open
	err = os.Remove(f.Name())
	fmt.Println("remove while open:", err)

	f.Close()
	err = os.Remove(f.Name())
	fmt.Println("remove after close:", err)
}

Output on Windows:

remove while open: remove C:\Users\kjk\AppData\Local\Temp\open-3149225719: The process cannot access the file because it is being used by another process.
remove after close: <nil>

Output on Linux:

remove while open: <nil>
remove after close: remove /tmp/open-349567551: no such file or directory

On Unix removing an open file only removes its name. The data stays available to the processes that have the file open and is freed when the last one closes it. You can use this on Unix to get a file that disappears even if the program crashes: create it, remove it right away, and keep using the *os.File. This doesn't work on Windows, so for portable code close first, then remove: defer os.Remove(name) followed by defer f.Close().

os.Exit skips deferred functions

defer os.RemoveAll(dir) doesn't run when the program calls os.Exit, log.Fatal or crashes because of an unhandled signal. A common way to keep cleanup working is to put the real work in a function that returns the exit code:

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func run() int {
	dir, err := os.MkdirTemp("", "job-*")
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		return 1
	}
	defer func() {
		os.RemoveAll(dir)
		fmt.Println("cleanup: temp dir removed")
	}()

	if err := os.WriteFile(filepath.Join(dir, "step1.out"), []byte("partial"), 0o644); err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		return 1
	}
	fmt.Println("step 2 failed, exiting with code 2")
	return 2 // deferred cleanup runs before we return
}

func main() {
	// os.Exit doesn't run deferred functions, so all the real work
	// (and all the defers) live in run()
	os.Exit(run())
}
step 2 failed, exiting with code 2
cleanup: temp dir removed

Clean up on Ctrl+C

By default, pressing Ctrl+C (SIGINT) or kill (SIGTERM) ends a Go program immediately, without running defers. To clean up, catch the signal with signal.NotifyContext and return normally from main:

package main

import (
	"context"
	"fmt"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"
	"time"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	dir, err := os.MkdirTemp("", "convert-*")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.RemoveAll(dir)
	fmt.Println("working in", filepath.Base(dir)[:8]+"...")

	select {
	case <-time.After(10 * time.Second): // stands in for long-running work
		fmt.Println("done")
	case <-ctx.Done():
		fmt.Println("interrupted, cleaning up")
	}
	// returning from main runs the deferred os.RemoveAll
}

Sending SIGINT after a second:

working in convert-...
interrupted, cleaning up

After the program exits, the convert-* directory is gone. See OS signals for more about signals.

Nothing helps with kill -9, a power failure or a crash in the middle of a write. If your program creates large temporary files, consider removing stale ones at startup (for example files matching myapp-* older than a day). Many Linux systems also clear /tmp on reboot and delete old files from it periodically (systemd-tmpfiles), so /tmp is not a place for anything you want to keep.

Working safely inside a temporary directory: os.Root

Programs often write files whose names come from untrusted input into a temporary directory: entries of a ZIP archive, names of uploaded files, paths in a request. A name like ../../.bashrc would escape the directory. os.Root (Go 1.24+) opens a directory and refuses any operation that would leave it, including through .. or symbolic links:

package main

import (
	"fmt"
	"os"
)

func main() {
	dir, err := os.MkdirTemp("", "jail-*")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.RemoveAll(dir)

	root, err := os.OpenRoot(dir)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer root.Close()

	// names coming from untrusted input, e.g. entries in an archive
	names := []string{"a.txt", "docs/b.txt", "../escape.txt", "/etc/passwd"}
	root.Mkdir("docs", 0o755)
	for _, name := range names {
		err := root.WriteFile(name, []byte("x"), 0o644)
		if err != nil {
			fmt.Printf("%-15s error: %v\n", name, err)
			continue
		}
		fmt.Printf("%-15s ok\n", name)
	}
}
a.txt           ok
docs/b.txt      ok
../escape.txt   error: openat ../escape.txt: path escapes from parent
/etc/passwd     error: openat /etc/passwd: path escapes from parent

Methods like WriteFile, ReadFile, MkdirAll and RemoveAll on os.Root were added in Go 1.25. See Application security for more on handling untrusted paths.

Temporary directories in tests

In tests, use t.TempDir(). It creates a new directory and registers a cleanup function that removes it, with everything inside, when the test and its subtests finish. There is no defer to forget. b.TempDir() in benchmarks and f.TempDir() in fuzz tests work the same way.

Here's a small package to test:

package notes

import (
	"os"
	"path/filepath"
	"strings"
)

// Save writes notes to dir/notes.txt, one per line.
func Save(dir string, notes []string) error {
	data := strings.Join(notes, "\n") + "\n"
	return os.WriteFile(filepath.Join(dir, "notes.txt"), []byte(data), 0o644)
}

// Load reads notes from notes.txt in the current directory.
func Load() ([]string, error) {
	data, err := os.ReadFile("notes.txt")
	if err != nil {
		return nil, err
	}
	return strings.Split(strings.TrimSuffix(string(data), "\n"), "\n"), nil
}

And its tests:

package notes

import (
	"os"
	"path/filepath"
	"slices"
	"testing"
)

func TestSave(t *testing.T) {
	dir := t.TempDir() // removed automatically when the test ends
	if err := Save(dir, []string{"buy milk", "call mom"}); err != nil {
		t.Fatal(err)
	}
	got, err := os.ReadFile(filepath.Join(dir, "notes.txt"))
	if err != nil {
		t.Fatal(err)
	}
	if string(got) != "buy milk\ncall mom\n" {
		t.Errorf("got %q", got)
	}
	rel, _ := filepath.Rel(os.TempDir(), dir)
	t.Logf("temp dir: %s", filepath.ToSlash(rel))
}

func TestLoad(t *testing.T) {
	dir := t.TempDir()
	// Chdir changes the working directory for this test only and
	// restores it when the test ends
	t.Chdir(dir)
	if err := Save(".", []string{"a", "b"}); err != nil {
		t.Fatal(err)
	}
	got, err := Load()
	if err != nil {
		t.Fatal(err)
	}
	if !slices.Equal(got, []string{"a", "b"}) {
		t.Errorf("got %v", got)
	}
}

func TestSubtests(t *testing.T) {
	for _, name := range []string{"empty", "one"} {
		t.Run(name, func(t *testing.T) {
			// every subtest (and every call) gets a fresh directory
			d1, d2 := t.TempDir(), t.TempDir()
			r1, _ := filepath.Rel(os.TempDir(), d1)
			r2, _ := filepath.Rel(os.TempDir(), d2)
			t.Logf("%s, %s", filepath.ToSlash(r1), filepath.ToSlash(r2))
		})
	}
}

var leftover string

func TestCleanupCheck(t *testing.T) {
	t.Run("inner", func(t *testing.T) {
		leftover = t.TempDir()
	})
	_, err := os.Stat(leftover)
	t.Logf("after subtest finished: exists=%v", err == nil)
}
$ go test -v
=== RUN   TestSave
    notes_test.go:23: temp dir: TestSave302010431/001
--- PASS: TestSave (0.00s)
=== RUN   TestLoad
--- PASS: TestLoad (0.00s)
=== RUN   TestSubtests
=== RUN   TestSubtests/empty
    notes_test.go:50: TestSubtestsempty798528267/001, TestSubtestsempty798528267/002
=== RUN   TestSubtests/one
    notes_test.go:50: TestSubtestsone289494825/001, TestSubtestsone289494825/002
--- PASS: TestSubtests (0.00s)
    --- PASS: TestSubtests/empty (0.00s)
    --- PASS: TestSubtests/one (0.00s)
=== RUN   TestCleanupCheck
=== RUN   TestCleanupCheck/inner
=== NAME  TestCleanupCheck
    notes_test.go:62: after subtest finished: exists=false
--- PASS: TestCleanupCheck (0.00s)
    --- PASS: TestCleanupCheck/inner (0.00s)
PASS

Things to notice:

If you need setup shared by many tests, combine os.MkdirTemp with t.Cleanup or TestMain; see Testing using setUp and tearDown function.

Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents