CreateTemp And MkdirTemp With Cleanup

os.CreateTemp and os.MkdirTemp generate collision-free names, and deferred Remove calls keep scratch files from leaking between runs.

GoCli Tooling

Code

gosnippet
44 lines
package main

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

func main() {
	// CreateTemp(dir, pattern):dir 传空串用 os.TempDir(),pattern 中 * 被随机串替换,文件固定 0600 权限
	f, err := os.CreateTemp("", "draft-*.txt")
	if err != nil {
		panic(err)
	}
	defer os.Remove(f.Name()) // 临时文件用完即删

	if _, err := f.WriteString("scratch payload\n"); err != nil {
		panic(err)
	}
	f.Close()

	data, err := os.ReadFile(f.Name())
	if err != nil {
		panic(err)
	}
	fmt.Printf("temp file %s: %q\n", filepath.Base(f.Name()), data)

	// MkdirTemp:临时目录里落多个工作文件,退出前整体清理
	dir, err := os.MkdirTemp("", "job-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)

	work := filepath.Join(dir, "result.txt")
	if err := os.WriteFile(work, []byte("done\n"), 0o644); err != nil {
		panic(err)
	}
	info, err := os.Stat(work)
	if err != nil {
		panic(err)
	}
	fmt.Printf("temp dir %s size %d\n", filepath.Base(dir), info.Size())
}

How it works

Count the function main as the entire surface area of CreateTemp And MkdirTemp With Cleanup.

Every err != nil branch (6 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

Watch out for

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Putting it to use

The demo output is labeled (temp file, temp dir), so each printed line points back to the operation that produced it.

Core lines under the microscope

if err != nil {
panic(err)
}
defer os.Remove(f.Name()) // 临时文件用完即删
defer os.RemoveAll(dir)

Interactive Tools for This Topic

FAQ

How are errors reported?
By aborting: each of the 6 `err != nil` branches calls `panic(err)`, so a failure stops the program at the point it is detected.
What does CreateTemp And MkdirTemp With Cleanup print when run?
Running the file directly is enough — expect labeled output lines such as `temp file`, `temp dir`.