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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.