Files, Directories, Paths, Temp Files, bufio & embed
"Methods on os.Root operate within the directory and do not permit paths that refer to locations outside the directory, including ones that follow symbolic links out of the directory." — Go 1.24 release notes, "Directory-limited filesystem access"
Summary: Files in Go are *os.File values wrapped around a file descriptor, directories and paths are plain strings and fs.FS values, and almost every real bug lives in the gaps: an unchecked Close, a half-written file after a crash, a path that escapes its directory, or a Scanner that quietly stops at 64 KiB. Focus: os.Open/Create/OpenFile flags and permissions, reading, writing and seeking, os.ReadFile/WriteFile, Stat, directories, ReadDir against filepath.WalkDir, symlinks, path against path/filepath, path traversal and os.Root, the io/fs abstraction with fstest, //go:embed and http.FS, temp files, bufio.Reader/Writer/Scanner, O_EXCL locking, atomic writes with fsync, large files, file watching and Windows differences. Learning goal: Open, write, replace, walk, serve and embed files so that a crash, a hostile file name or a very long line cannot corrupt data or surprise you, and say which Go primitive gives which guarantee.
This page owns the file system API of the standard library. It does not re-teach its neighbours: the io.Reader and io.Writer contract, io.Pipe, io.TeeReader and the rest of composition live in The io Package: Readers, Writers, Pipes & Composition; error values, errors.Is/errors.As and defer live in Errors, Wrapping, Panic, Recover & Defer; JSON and CSV encoding of file contents is in JSON, XML, Struct Tags, Encoder/Decoder, Base64; signals and process exit are in OS Processes, Signals & Graceful Shutdown; http.FileServer as a server is in net/http: Servers, Clients, Handlers & Routing; multipart uploads and S3 are in File Uploads, S3 & Serving from a CDN; what a disk flush costs inside a database is in Durability, WAL & Crash Recovery. Here each gets one honest paragraph and a link.
Facts below come from the package documentation of os, io/fs, embed, bufio, path/filepath and testing/fstest (read with go doc from the installed toolchain and cross-checked against the sources at go.dev/src), the Go 1.16, 1.20, 1.21, 1.23, 1.24 and 1.25 release notes, the Go blog post "Traversal-resistant file APIs", Effective Go and the PHP manual for the comparison. Snippets are in a module with go 1.24 in go.mod; all of them pass gofmt, go vet and go test -race.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why files need so much care | Why it exists |
Which Go release added embed, io/fs, os.Root | Where it comes from |
os.Open against os.Create against os.OpenFile | Opening files |
0o644, FileMode, umask | Permissions and umask |
Read, Write, Seek, Close returning an error | Reading, writing, seeking, closing |
os.ReadFile, os.WriteFile, os.Stat, FileInfo | Whole-file helpers and Stat |
MkdirAll, Remove, RemoveAll, Rename, ReadDir | Directories |
filepath.WalkDir, SkipDir, symlinks | Walking a tree |
path against path/filepath, Join, Clean, Rel, Glob | path and path/filepath |
../../etc/passwd, filepath.IsLocal, os.Root | Path traversal |
fs.FS, fs.Sub, fstest.MapFS | io/fs |
//go:embed, embed.FS, http.FS | embed |
os.CreateTemp, os.MkdirTemp, t.TempDir() | Temp files and directories |
bufio.Scanner, token too long, ReadString, Flush | bufio |
Crash-safe replace, fsync, durability | Atomic writes and fsync |
Lock files, O_EXCL, flock | Locking and O_EXCL |
Multi-gigabyte files, io.Copy, io.SectionReader | Large files |
fsnotify, config reload | Watching files |
| Windows separators, reserved names, no atomic rename | Windows differences |
| Error texts and version gates | Mechanics |
| Upload store, config reload, log rotation in code | Solving the classic problems |
| Which API for which job | Choosing |
| One process to many services | In architecture |
file_get_contents, fopen, SplFileObject | For PHP/Laravel developers |
| Run it yourself | Lab |
Everything in one minute
| API | Plain words | Tiny example | Gotcha |
|---|---|---|---|
os.Open | Open a file read-only | f, err := os.Open("a.txt") | Fails if it does not exist; you must Close |
os.Create | Create or truncate, then read-write | f, err := os.Create("a.txt") | Silently empties an existing file |
os.OpenFile | Choose flags and permissions yourself | os.OpenFile(p, os.O_WRONLY, 0o644) | The permission argument only matters when the file is created |
os.ReadFile | Whole file into memory | b, err := os.ReadFile(p) | A 5 GiB file becomes 5 GiB of heap |
os.WriteFile | Create or truncate, write, close | os.WriteFile(p, b, 0o644) | Not atomic; a crash can leave a partial file |
os.Stat | Metadata without opening | fi, err := os.Stat(p) | Follows symlinks; Lstat does not |
os.MkdirAll | mkdir -p | os.MkdirAll(dir, 0o755) | Returns nil when it already exists |
os.RemoveAll | rm -rf | os.RemoveAll(dir) | Returns nil when the path is missing; typos delete trees |
os.Rename | Move or replace | os.Rename(tmp, final) | Atomic only on one file system, not on Windows |
os.ReadDir | One directory level, sorted | ents, err := os.ReadDir(d) | Not recursive |
filepath.WalkDir | Whole tree, lexical order | filepath.WalkDir(root, fn) | Does not follow symlinks |
filepath.Join | Join and clean | filepath.Join(base, name) | Does not stop ../ escapes |
filepath.IsLocal | Is this name safe to join? | filepath.IsLocal(name) | Lexical only; a symlink inside can still escape |
os.OpenRoot | Directory-limited file access | r, _ := os.OpenRoot(dir) | Does not limit mount points |
fs.FS | Read-only tree interface | fs.ReadFile(fsys, "a/b") | Slash paths, no .., no leading / |
//go:embed | Put files into the binary | //go:embed static | No .., no symlinks, dotfiles skipped |
os.CreateTemp | Private unique file | os.CreateTemp("", "x-*.json") | You must remove it |
bufio.Scanner | Read lines or tokens | sc.Scan() | Stops at 64 KiB per token, check sc.Err() |
bufio.Writer | Batch small writes | bw.Flush() | Data is lost without Flush |
f.Sync | fsync: push to disk | f.Sync() | Needed before the rename for durability |
| Go version | What changed for files | Where |
|---|---|---|
| 1.16 | io/fs, embed, os.ReadFile, os.WriteFile, os.ReadDir, os.CreateTemp, os.MkdirTemp, os.DirFS; io/ioutil deprecated | io/fs, embed |
| 1.15 | testing.T.TempDir | Temp files |
| 1.20 | filepath.IsLocal | Path traversal |
| 1.21 | slices, maps, min/max help with directory results | Walking a tree |
| 1.23 | filepath.Localize, os.CopyFS | Path traversal |
| 1.24 | os.Root, os.OpenRoot, os.OpenInRoot, Root.FS | Path traversal |
| 1.25 | io/fs.ReadLinkFS; Root.ReadFile, WriteFile, MkdirAll, RemoveAll, Rename and more | Path traversal, io/fs |
| Mistake | Symptom | Section |
|---|---|---|
Ignoring the error from Close after writing | Silent data loss on a full disk or NFS | Reading, writing, seeking, closing |
os.WriteFile over a live config | Reader sees an empty or half file | Atomic writes and fsync |
Rename without fsync first | New name, zero bytes after power loss | Atomic writes and fsync |
filepath.Join(base, userInput) | Reads /etc/passwd | Path traversal |
bufio.Scanner on a long line | bufio.Scanner: token too long, loop ends early | bufio |
Forgetting bufio.Writer.Flush | Last lines never written | bufio |
defer f.Close() in a loop over many files | Too many open files | Reading, writing, seeking, closing |
//go:embed ../x | invalid pattern syntax | embed |
| Rename across file systems | invalid cross-device link | Atomic writes and fsync |
| Lock file left by a crashed process | Service refuses to start | Locking and O_EXCL |
Why it exists
A file looks simple because the API is small: open, read, write, close. The difficulty is that the operating system promises very little. A write returns when the bytes are in the kernel's page cache, not on the disk. A rename is atomic, but the data it points to may not be. A path is a string that the kernel interprets, one component at a time, following symbolic links, at the moment you call it, not at the moment you checked it. Go's standard library gives thin, honest wrappers and leaves the policy to you; this page is the policy.
| Naive assumption | What the system really does | Consequence |
|---|---|---|
Write returned, so the data is saved | It is in the page cache; the disk may be seconds behind | A power cut loses it unless you Sync |
Close cannot fail | Close can report a deferred write error | A full disk or a lost NFS mount shows up only there |
| A path names one file | A path is resolved at use time through symlinks and .. | Check-then-open races (TOCTOU) |
Rename replaces a file safely | Atomic name switch, but only inside one file system | Cross-device rename fails; Windows is not atomic |
| A line is a short string | Lines can be any length | Scanner stops at 64 KiB by default |
| Files are on a disk | Files can be on NFS, overlayfs, tmpfs, a ConfigMap mount | Latency, locking and rename semantics differ |
Everyday picture: a filing clerk. Write is handing a page to the clerk, who puts it in the out-tray (page cache). Sync is waiting until the clerk has walked it to the cabinet. Rename is swapping the label on a folder: instant and all-or-nothing, but only meaningful if the new folder was already filled and stored. A path is directions given to the clerk ("third door, then up one floor"); a symbolic link is a sign on the way saying "actually go to another building".
Three common misunderstandings, up front
- "
os.WriteFileis safe for config files." It truncates first and writes second, so a crash or a concurrent reader sees an empty or partial file; the documentation says so itself: "a failure mid-operation can leave the file in a partially written state". Write a temp file and rename it. - "
filepath.Joinsanitises paths." It only cleans them;Join("/srv/public", "../secret")is/srv/secret. Validate withfilepath.IsLocal, or better, open throughos.Root. - "
bufio.Scannerreads any text file." It reads tokens up to 64 KiB, and when a token is longer it stops and reports the problem only throughsc.Err(), which most loops never look at.
Where it comes from
The Unix file API (open, read, write, lseek, close, rename, fsync) is the model; Go's os package wraps those calls with *os.File, *fs.PathError and portable flag constants. Until Go 1.15 the helpers lived in io/ioutil; the Go 1.16 release notes moved them ("ReadFile => os.ReadFile", "TempDir => os.MkdirTemp", "TempFile => os.CreateTemp", "WriteFile => os.WriteFile") and introduced the two ideas that organise this page: io/fs, "an abstraction for read-only trees of files", and embed, files "embedded in the program during compilation".
| Change | Release | Primary source |
|---|---|---|
io/fs, fs.FS, os.DirFS, os.ReadDir, os.ReadFile | Go 1.16 | go.dev/doc/go1.16 |
//go:embed and package embed | Go 1.16 | go.dev/doc/go1.16 |
filepath.IsLocal ("lexically local to a directory") | Go 1.20 | go.dev/doc/go1.20 |
filepath.Localize, os.CopyFS | Go 1.23 | go.dev/doc/go1.23 |
os.Root, os.OpenRoot, os.OpenInRoot | Go 1.24 | go.dev/doc/go1.24, go.dev/blog/osroot |
fs.ReadLinkFS, more Root methods | Go 1.25 | go.dev/doc/go1.25 |
Path traversal as a class of bug is older than Go. The Go blog post that introduced os.Root (Damien Neil, 12 March 2025) explains why sanitising strings was never enough: "Path sanitization is not sufficient when attackers may have access to part of the local filesystem." That sentence is the reason the traversal section below ends with os.Root and not with IsLocal.
The concept catalogue
Opening files: Open, Create and OpenFile Must-know
In plain words: os.Open opens an existing file for reading, os.Create makes a new empty file (or empties an existing one), and os.OpenFile lets you pick the flags and the permission bits yourself. All three give back a *os.File you must close.
Common misunderstanding: "os.Create creates a file." It creates or truncates: if the file exists, its contents are gone the moment Create returns. To create only when absent, use OpenFile with O_CREATE and O_EXCL.
Definition: os.Open(name) is OpenFile(name, O_RDONLY, 0). os.Create(name) is OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0o666). The flags are the POSIX open(2) flags: exactly one of O_RDONLY, O_WRONLY, O_RDWR, ORed with any of O_APPEND, O_CREATE, O_EXCL, O_SYNC, O_TRUNC. On failure the error is a *fs.PathError whose Op is "open".
step call result
1 os.OpenFile("a", O_WRONLY|O_CREATE|O_EXCL, 0o644) created, fd 3
2 os.OpenFile("a", O_WRONLY|O_CREATE|O_EXCL, 0o644) error: open a: file exists (errors.Is(err, fs.ErrExist))
3 os.OpenFile("a", O_WRONLY|O_CREATE, 0o600) opens existing; mode 0o600 is ignored
4 os.OpenFile("a", O_WRONLY|O_TRUNC, 0) length becomes 0 immediately
5 os.OpenFile("a", O_WRONLY|O_APPEND, 0) every Write goes to the current endReal scenarios: a service that creates its PID file only if none exists; an audit log opened with O_APPEND by several processes; an upload handler that must never overwrite an existing object; an import job that opens the input with Open and the report with Create.
| Flag | Meaning | Typical use | Gotcha |
|---|---|---|---|
O_RDONLY | read only | os.Open | writing fails with bad file descriptor |
O_WRONLY | write only | logs, output | reading fails |
O_RDWR | read and write | os.Create, databases | one shared offset for both |
O_CREATE | create when missing | most writers | needs a permission argument |
O_EXCL | with O_CREATE: fail if present | locks, unique files | on a network file system, check that your mount honours it |
O_TRUNC | empty a regular file on open | rewriting | data loss before you write anything |
O_APPEND | writes go to the end | logs | WriteAt returns an error on such a file |
O_SYNC | each write waits for the disk | rare, slow | usually Sync() at checkpoints instead |
Fix / how to use it: create-if-absent with an exclusive flag and a deferred Close that keeps its error:
// Package openflags shows os.OpenFile flags, permissions, exclusive creation
// and why the error from Close matters.
package openflags
import (
"errors"
"fmt"
"io/fs"
"os"
)
// CreateNew creates path and fails if it already exists (O_CREATE|O_EXCL).
// The kernel performs check-and-create as one step, so two processes cannot
// both succeed.
func CreateNew(path string, data []byte, perm fs.FileMode) (err error) {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
if err != nil {
return err // wraps fs.ErrExist when the file is already there
}
// Close can report a delayed write error (NFS, quota); never drop it.
defer func() {
if cerr := f.Close(); err == nil {
err = cerr
}
}()
_, err = f.Write(data)
return err
}
// Append adds one line to a log file. O_APPEND makes the kernel move the
// offset to the end for every write call.
func Append(path, line string) (err error) {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o644)
if err != nil {
return err
}
defer func() {
if cerr := f.Close(); err == nil {
err = cerr
}
}()
_, err = fmt.Fprintln(f, line)
return err
}
// ErrLocked is returned when another process already holds the lock file.
var ErrLocked = errors.New("lock file exists")
// Lock takes an advisory lock by creating path exclusively. The returned
// function releases it. A crash leaves a stale file behind; see the page.
func Lock(path string) (unlock func() error, err error) {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
if errors.Is(err, fs.ErrExist) {
return nil, ErrLocked
}
return nil, err
}
if _, err := fmt.Fprintf(f, "%d\n", os.Getpid()); err != nil {
f.Close()
os.Remove(path)
return nil, err
}
if err := f.Close(); err != nil {
os.Remove(path)
return nil, err
}
return func() error { return os.Remove(path) }, nil
}Permissions, FileMode and umask Important
In plain words: a file's permission bits say who may read, write and execute it. When you create a file you ask for bits, and the process's umask removes some of them, so the file you get can be more private than the one you asked for, never less.
Common misunderstanding: "os.WriteFile(p, b, 0o644) always produces a 0644 file." The bits apply only when the file is created, they are masked by the umask, and an existing file keeps its old mode.
Definition: fs.FileMode is a uint32 holding the type bits (ModeDir, ModeSymlink, ModeNamedPipe, ModeSocket, ModeDevice) and the nine permission bits, retrievable with Mode().Perm(). The kernel computes perm & ~umask; the common umask 022 turns 0o666 into 0o644 and 0o777 into 0o755. os.Chmod sets the exact bits afterwards and is not filtered.
step actor what happens
1 process umask 0o077 inherited from the shell or the service manager
2 os.OpenFile(p, O_CREATE|O_WRONLY, 0o666) kernel creates mode 0o666 &^ 0o077 = 0o600
3 os.Stat(p).Mode().Perm() -rw-------
4 os.Chmod(p, 0o644) -rw-r--r-- (chmod ignores the umask)Real scenarios: private keys that must be 0o600 (an SSH client refuses looser ones); a log directory writable by a group; a Docker image running as a non-root user whose umask differs from your laptop; a test that passes locally and fails in CI because the umask differs.
| Octal | Symbolic | Used for |
|---|---|---|
0o600 | -rw------- | secrets, keys, temp files from CreateTemp |
0o644 | -rw-r--r-- | ordinary files |
0o640 | -rw-r----- | files shared with a group |
0o700 | drwx------ | private directories, MkdirTemp |
0o755 | drwxr-xr-x | public directories, binaries |
0o666 / 0o777 | before umask | what Create and MkdirAll callers often ask for |
Fix / how to use it: state the mode you need and, for secrets, call Chmod or open with 0o600. The TestUmaskFiltersPerm test in the snippet above sets the umask to 0o077 and shows a requested 0o666 arriving as 0o600. In Go write octal as 0o644, not 0644 (both compile; the first is unambiguous).
Reading, writing, seeking and closing Must-know
In plain words: a *os.File is a handle with a cursor. Read and Write move the cursor, Seek jumps it, ReadAt and WriteAt ignore it, and Close hands the descriptor back to the kernel and tells you whether anything went wrong.
Common misunderstanding: "defer f.Close() is enough." For a file you only read, yes. For a file you write, Close is the last chance to learn that the data did not make it (a quota, a full disk, NFS), and ignoring its error hides the failure.
Definition: Read(p) returns n, err where n > 0 data may come with io.EOF; always process p[:n] first. Write returns a non-nil error whenever n < len(p). Seek(off, whence) uses io.SeekStart, io.SeekCurrent, io.SeekEnd. ReadAt is safe for concurrent use on one file because it does not touch the cursor; Read and Write from several goroutines share one cursor and interleave. Sync flushes to stable storage. A second Close returns os.ErrClosed.
step goroutine A goroutine B file offset
1 f.Read(buf[:4]) 0 -> 4
2 f.Read(buf[:4]) 4 -> 8 (shared cursor)
3 f.ReadAt(buf[:4], 0) 8 (unchanged)
4 f.Close() fd released
5 f.Read(buf) error: read a: file already closedReal scenarios: a log shipper that remembers the byte offset it last read and resumes with Seek; a parallel checksum with several goroutines reading disjoint ranges via ReadAt; an export that writes a CSV and must fail the HTTP request if Close reports an error; a loop over ten thousand files that opens all of them because the defer waits for the function, not the iteration (move the body into a helper function).
| Operation | Returns | Error you will see |
|---|---|---|
Read at the end | 0, io.EOF | EOF is a normal end, not a failure |
Write on a read-only file | 0, err | write f: bad file descriptor |
Write after Close | 0, err | write f: file already closed |
ReadAt past the end | short count, io.EOF | EOF |
Seek before the start | 0, err | seek f: invalid argument |
Close twice | err | close f: file already closed |
Fix / how to use it: the pattern from CreateNew above keeps the first error:
defer func() {
if cerr := f.Close(); err == nil {
err = cerr
}
}()Whole-file helpers and Stat Must-know
In plain words: os.ReadFile and os.WriteFile do open, transfer and close in one call. os.Stat asks the file system about a path (size, mode, modification time, is it a directory) without opening it.
Common misunderstanding: "os.ReadFile returns io.EOF at the end." It does not: "A successful call returns err == nil, not err == EOF." And os.WriteFile is not atomic: it truncates, writes and closes as separate system calls.
Definition: os.Stat(name) returns an fs.FileInfo (Name, Size, Mode, ModTime, IsDir, Sys) and follows symlinks; os.Lstat describes the link itself. A missing path gives an error satisfying errors.Is(err, fs.ErrNotExist). Prefer that test to os.IsNotExist, which does not unwrap errors.
step call meaning
1 fi, err := os.Stat(p) one stat(2); no descriptor is opened
2 errors.Is(err, fs.ErrNotExist) true: the path is absent (or a parent is not a directory)
3 fi.Mode().IsRegular() true for plain files; false for dirs, symlinks, devices
4 os.Stat then os.Open two steps: the file can change in between (TOCTOU)Real scenarios: reject an upload that is larger than a limit before reading it; skip unchanged files in a build tool by comparing ModTime and Size; read a small config at start-up with ReadFile; refuse to follow a symlink in a deploy script with Lstat.
| Need | Use | Note |
|---|---|---|
| Does the path exist? | os.Stat and errors.Is(err, fs.ErrNotExist) | existence checks before use are racy; just open and handle the error |
| Regular file or directory? | fi.Mode().IsRegular(), fi.IsDir() | Stat follows links |
| Is it a symlink? | os.Lstat then Mode()&fs.ModeSymlink != 0 | |
| Same file? | os.SameFile(fi1, fi2) | compares device and inode on Unix |
| Size of a file you will stream | fi.Size() | not meaningful for pipes and /proc files |
Fix / how to use it: do not check-then-open. Open and handle fs.ErrNotExist; use Stat for information, not for permission.
Directories: MkdirAll, Remove, RemoveAll, Rename, ReadDir Must-know
In plain words: directories are files that list names. MkdirAll builds a whole chain, Remove deletes one empty thing, RemoveAll deletes a tree, Rename moves a name, and ReadDir lists one level in sorted order.
Common misunderstanding: "os.Rename is always an atomic replace." The documentation is careful: "If newpath already exists and is not a directory, Rename replaces it. If newpath already exists and is a directory, Rename returns an error. OS-specific restrictions may apply when oldpath and newpath are in different directories. Even within the same directory, on non-Unix platforms Rename is not an atomic operation."
Definition: os.Mkdir(p, perm) fails if the parent is missing or p exists; os.MkdirAll creates parents and returns nil if p is already a directory. os.Remove removes a file or an empty directory (directory not empty otherwise). os.RemoveAll returns nil if the path does not exist. os.ReadDir returns []fs.DirEntry sorted by file name, with the type available without a stat call. os.Rename returns *os.LinkError and, across file systems, an EXDEV error.
step call result (real output from the lab, macOS)
1 os.Open("missing.txt") open missing.txt: no such file or directory
2 os.Rename("f", "d") // d is a dir rename f d: file exists
3 os.ReadFile("d") read d: is a directory
4 os.Remove("d") // not empty remove d: directory not empty
5 os.RemoveAll("nothing") <nil>Real scenarios: create uploads/2026/11/ on demand with MkdirAll; clear a scratch directory with RemoveAll; rotate app.log to app.log.1 with Rename; list a plugin directory with ReadDir and keep only names ending in .so.
| Call | Missing parent | Already exists | Non-empty directory |
|---|---|---|---|
os.Mkdir | error no such file or directory | error file exists | not applicable |
os.MkdirAll | creates parents | nil if a directory; error if a file | not applicable |
os.Remove | error no such file or directory | removes it | error directory not empty |
os.RemoveAll | nil | removes tree | removes tree |
os.Rename | error | replaces a file; errors on a directory target (per the documentation) | not applicable |
Fix / how to use it: treat RemoveAll like rm -rf: never call it with a path built from user input or an empty string variable that could resolve to . or /. Build the path from a base you control, and prefer os.Root.RemoveAll (Go 1.25) when part of the name is untrusted.
Walking a tree: ReadDir against WalkDir Important
In plain words: ReadDir lists one folder. filepath.WalkDir visits every file and folder below a starting point, in a stable order, calling your function once for each.
Common misunderstanding: "WalkDir follows symlinks, so it finds everything." It does not follow symbolic links found inside the tree (if the root itself is a link, its target is walked). That protects you from loops and from escaping the tree, and it means a linked directory appears as one entry of type symlink.
Definition: filepath.WalkDir(root, fn) calls fn(path, d fs.DirEntry, err error). Returning filepath.SkipDir from a directory skips it (from a file, skips the rest of the parent directory); returning filepath.SkipAll ends the walk (Go 1.20); any other error stops the walk and is returned. fn is also called with a non-nil err when a directory cannot be read, and you decide what to do. WalkDir reads a whole directory into memory before walking it. It is faster than the older filepath.Walk because it avoids an lstat per entry.
step callback returns effect
1 fn(".", dir, nil) nil descend
2 fn("node_modules", dir, nil) SkipDir the whole subtree is ignored
3 fn("a", dir, nil) nil descend
4 fn("a/one.txt", file, nil) nil
5 fn("link", symlink, nil) nil not followed, type is ModeSymlink
6 fn("secret", dir, permission denied) err you choose: return err, or nil to continueReal scenarios: a static-site builder collecting .md files; a backup tool computing total size; a linter skipping vendor and .git; a cleanup job removing files older than 30 days; a search index crawler that must not follow symlinks into /proc.
| Need | Use | Cost |
|---|---|---|
| One folder, sorted | os.ReadDir | one directory read |
| One folder, unsorted, streaming | (*os.File).ReadDir(n) | batches of n entries |
| Whole tree, no stat | filepath.WalkDir | one directory read per folder |
| Whole tree with sizes | WalkDir and d.Info() | an extra lstat per entry |
Whole tree on an fs.FS | fs.WalkDir | slash paths, works on embed.FS |
| Match a pattern | filepath.Glob, fs.Glob | not recursive, ** is not supported |
Fix / how to use it: keep file-type tests on the DirEntry (free) and call Info() only for entries you keep:
// Package walk compares os.ReadDir (one level) with filepath.WalkDir (tree)
// and shows how symlinks and SkipDir behave.
package walk
import (
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
)
// Names lists one directory level, sorted by name (os.ReadDir sorts for you).
func Names(dir string) ([]string, error) {
ents, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
out := make([]string, 0, len(ents))
for _, e := range ents {
n := e.Name()
if e.IsDir() {
n += "/"
}
out = append(out, n)
}
return out, nil
}
// Tree walks root, skips directories named skip, and reports every entry
// with its type. WalkDir does not follow symbolic links.
func Tree(root, skip string) ([]string, error) {
var out []string
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err // e.g. permission denied; decide, do not ignore
}
rel, _ := filepath.Rel(root, path)
if d.IsDir() && d.Name() == skip {
return filepath.SkipDir
}
kind := "file"
switch {
case d.Type()&fs.ModeSymlink != 0:
kind = "symlink"
case d.IsDir():
kind = "dir"
}
out = append(out, kind+" "+filepath.ToSlash(rel))
return nil
})
sort.Strings(out)
return out, err
}
// TotalSize sums regular files only. Calling d.Info() costs an lstat per
// entry; DirEntry.Name and Type come free from the directory read.
func TotalSize(root string) (n int64, err error) {
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.Type().IsRegular() {
return nil
}
fi, err := d.Info()
if err != nil {
return err
}
n += fi.Size()
return nil
})
return n, err
}
// Ext counts files by extension, using fs.FS so tests need no disk.
func Ext(fsys fs.FS) (map[string]int, error) {
m := map[string]int{}
err := fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
m[strings.ToLower(filepath.Ext(p))]++
return nil
})
return m, err
}path and path/filepath Must-know
In plain words: path treats / as the only separator and is for URLs and io/fs names; path/filepath uses the separator of the operating system (/ on Linux and macOS, \ on Windows) and is for real files.
Common misunderstanding: "filepath.Join works like PHP string concatenation or Python's os.path.join." Join cleans the result and does not let a later absolute element reset the path: Join("/srv", "/etc/passwd") is /srv/etc/passwd, and Join("/srv/app", "../../etc/passwd") is /etc/passwd.
Definition: Clean removes . and empty elements, resolves .. lexically and returns . for an empty result. Join joins elements with the separator and calls Clean. Base is the last element, Dir is everything before it, Ext is the suffix from the last dot. Abs prefixes the working directory. Rel(base, target) computes a relative path and fails when no relative path exists (for example different Windows drives, or an absolute target with a relative base). Match(pattern, name) supports *, ?, [...] and \ escapes, and * never matches a separator. Glob returns the matching files and an empty slice, with a nil error, when nothing matches; the only possible error is filepath.ErrBadPattern. filepath.EvalSymlinks resolves links on the disk, which Clean never does. path.Join and path.Clean behave the same lexically but with / only.
step call result
1 path.Clean("a//b/./c/..") a/b
2 path.Clean("/../x") /x (cannot go above root)
3 path.Clean("../../a") ../../a (relative paths keep leading ..)
4 filepath.Join("/srv", "/etc/passwd") /srv/etc/passwd
5 filepath.Rel("/a/b", "/a/x") ../x
6 filepath.Match("*.go", "dir/main.go") false (* does not cross a separator)Real scenarios: building the destination of a generated file; deriving a URL route from a file name (use path, because a URL has slashes even on Windows); finding all *.log files with Glob; turning an absolute path into a project-relative one for a report; computing a cache key from Ext.
| Function | path | path/filepath | Note |
|---|---|---|---|
| Separator | always / | os.PathSeparator | filepath.ToSlash and FromSlash convert |
Join, Clean, Base, Dir, Ext, Split, Match | yes | yes | same lexical rules |
Abs, Rel, EvalSymlinks, Glob, WalkDir | no | yes | need the OS |
IsAbs, IsLocal, Localize, VolumeName | IsAbs only | yes | Windows aware |
| Typical use | URLs, io/fs, archive names | files on disk | pick by what the string names |
Fix / how to use it: never mix the two. Use filepath when the string will reach the OS and path when it is a URL or an fs.FS name. The safe-join helper and its tests (including the IsLocal table) are here:
// Package paths shows path vs path/filepath and safe joining of untrusted
// names.
package paths
import (
"errors"
"io/fs"
"path"
"path/filepath"
)
// URLJoin uses package path: always forward slashes (URLs, io/fs names).
func URLJoin(elem ...string) string { return path.Join(elem...) }
// OSJoin uses path/filepath: the separator of the running OS.
func OSJoin(elem ...string) string { return filepath.Join(elem...) }
// ErrUnsafe is returned for names that could leave the base directory.
var ErrUnsafe = errors.New("unsafe path")
// SafeJoin joins base and an untrusted slash-separated name taken from, for
// example, a URL or an archive entry. filepath.IsLocal rejects "..", absolute
// names, empty names and (on Windows) reserved names such as NUL.
func SafeJoin(base, name string) (string, error) {
local, err := filepath.Localize(name) // slash path to OS path, Go 1.23+
if err != nil || !filepath.IsLocal(local) {
return "", ErrUnsafe
}
return filepath.Join(base, local), nil
}
// FSName validates a name for io/fs: slash separated, unrooted, no "." or
// ".." elements (except the single name ".").
func FSName(name string) error {
if !fs.ValidPath(name) {
return &fs.PathError{Op: "open", Path: name, Err: fs.ErrInvalid}
}
return nil
}
// Under reports where target sits relative to base, or an error when the two
// have no common root (for example different Windows drives).
func Under(base, target string) (string, error) { return filepath.Rel(base, target) }Path traversal: IsLocal, ValidPath and os.Root Must-know
In plain words: path traversal is an attacker getting your program to open a file outside the folder you meant by putting ../ or a symbolic link into a name. Three tools stop it in layers: check the name, check it against an fs.FS rule, or let the kernel confine every access.
Common misunderstanding: "I called filepath.Clean and checked the prefix, so it is safe." Cleaning is lexical; it cannot see symbolic links, and a check followed by an open leaves a window for a race (TOCTOU). The Go blog states both limits and the cure.
Definition: filepath.IsLocal(p) (Go 1.20) is true when the path, by lexical analysis only, "is within the subtree rooted at the directory in which path is evaluated", is not absolute, is not empty, and on Windows is not a reserved name such as NUL. If it is true, Join(base, p) always produces a path contained in base. filepath.Localize(slashPath) (Go 1.23) converts a slash-separated name from a URL or archive to an OS path and returns an error for unsafe names. fs.ValidPath(name) is the matching rule for io/fs names: slash-separated, unrooted, no . or .. elements except the single name .. os.OpenRoot(dir) (Go 1.24) returns an *os.Root whose methods (Open, Create, OpenFile, Mkdir, Stat, Lstat, Remove, OpenRoot, FS; since Go 1.25 also ReadFile, WriteFile, MkdirAll, RemoveAll, Rename, Readlink, Symlink, Link, Chmod, Chown, Chtimes) refuse any name that leaves the directory by .. or by a symlink, with the error path escapes from parent. os.OpenInRoot(dir, name) is the one-call form.
step attacker input Join(base, name) + Open IsLocal + Open Root.Open
1 ../secret.txt reads outside rejected rejected: path escapes from parent
2 /etc/passwd Join keeps it under base rejected rejected
3 link (symlink to ../secret) follows link, reads outside follows link, reads rejected: path escapes from parent
4 a/../b ok ok ok (stays inside)
5 name valid at check time, race: link swapped race no gap: each step is relative to a handle
replaced by a symlink laterReal scenarios: an image proxy that serves /files/{name}; a ZIP or tar extractor (the "zip slip" bug is exactly a traversal name inside an archive); a plugin loader reading plugins/<name>/manifest.json; a multi-tenant app that stores tenant files under data/<tenant>/; a container runtime or CI runner exposing a workspace folder to untrusted jobs.
| Defence | Stops ../x | Stops absolute names | Stops symlink escape | Stops TOCTOU | Go version |
|---|---|---|---|---|---|
strings.HasPrefix(Clean(p), base) | partly, easy to get wrong | no | no | no | any |
filepath.IsLocal(name) | yes | yes | no | no | 1.20 |
filepath.Localize(name) | yes | yes | no | no | 1.23 |
fs.ValidPath(name) | yes | yes | no (depends on the FS) | no | 1.16 |
os.DirFS(dir) alone | validates names | validates names | no ("DirFS is therefore not a general substitute for a chroot-style security mechanism") | no | 1.16 |
os.Root / os.OpenInRoot | yes | yes | yes | yes | 1.24 |
Root.FS() | yes | yes | yes | yes | 1.24 |
Fix / how to use it: validate the shape of the name with IsLocal (cheap, gives a good error message), then perform the access through an os.Root. The snippet below shows three functions and tests that read the same inputs: the naive join leaks, the lexical check stops only .., os.Root stops both. Limits: Root does not stop a mount point inside the tree, and on Linux it relies on openat-style calls, so it is not a sandbox against a hostile process that can mount file systems.
// Package rootdemo contrasts filepath.Join with os.Root (Go 1.24) for
// untrusted file names.
package rootdemo
import (
"os"
"path/filepath"
)
// NaiveRead joins an untrusted name onto base. It is vulnerable to "../".
func NaiveRead(base, name string) ([]byte, error) {
return os.ReadFile(filepath.Join(base, name))
}
// LexicalRead validates the name with filepath.IsLocal first. That stops
// "../x" and absolute paths, but not a symlink already inside base.
func LexicalRead(base, name string) ([]byte, error) {
if !filepath.IsLocal(name) {
return nil, &os.PathError{Op: "read", Path: name, Err: os.ErrInvalid}
}
return os.ReadFile(filepath.Join(base, name))
}
// RootRead opens base as an os.Root; the kernel resolves each component
// relative to a directory descriptor, so neither ".." nor symlinks can leave.
func RootRead(base, name string) ([]byte, error) {
root, err := os.OpenRoot(base)
if err != nil {
return nil, err
}
defer root.Close()
f, err := root.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return nil, err
}
buf := make([]byte, fi.Size())
n, err := f.Read(buf)
if n == len(buf) {
err = nil
}
return buf[:n], err
}io/fs: the file system as an interface Must-know
In plain words: fs.FS is a read-only tree of files with one method, Open(name). Disk folders, embedded files, zip archives and in-memory test trees all implement it, so one function can read from any of them.
Common misunderstanding: "fs.FS is just a wrapper around os.Open." It has stricter rules: names are always slash-separated, never start with /, never contain .., and the root is the single name .. On Windows os.DirFS("C:/data") still uses / names.
Definition: type FS interface { Open(name string) (File, error) }. Optional interfaces speed things up and are discovered with a type assertion by helpers: fs.ReadFileFS, fs.ReadDirFS, fs.StatFS, fs.GlobFS, fs.SubFS, and since Go 1.25 fs.ReadLinkFS. Helpers: fs.ReadFile, fs.ReadDir, fs.Stat, fs.WalkDir, fs.Glob, fs.Sub (a view of a subdirectory, no copying), fs.ValidPath. In tests, testing/fstest provides fstest.MapFS (an in-memory FS built from a map) and fstest.TestFS(fsys, expected...), which checks that an implementation follows the contract.
step call what happens
1 fs.ReadFile(fsys, "docs/a.txt") uses fsys.ReadFile if implemented, else Open + read all
2 fs.Sub(fsys, "docs") new FS rooted at docs; "a.txt" is now "docs/a.txt"
3 fs.ReadFile(sub, "../greeting.txt") error: invalid argument (not a valid path)
4 fstest.TestFS(mapFS, "docs/a.txt") walks the FS, checks Open/Stat/ReadDir are consistentReal scenarios: a CLI that accepts os.DirFS(flagDir) in production and fstest.MapFS in unit tests, with no temp directories; a template loader (template.ParseFS) reading from an embedded tree; a migration runner reading *.sql files from embed.FS; a linter that works the same on a directory and on a zip.
| Provider | Package | Writable? | Notes |
|---|---|---|---|
os.DirFS(dir) | os | no | symlinks can leave dir; use Root.FS to confine |
(*os.Root).FS() | os | no | confined, Go 1.24 |
embed.FS | embed | no | compile-time snapshot |
fstest.MapFS | testing/fstest | build it in code | Data, Mode, ModTime per entry |
zip.Reader | archive/zip | no | implements fs.FS |
fs.Sub(fsys, dir) | io/fs | no | cheap view |
os.CopyFS(dir, fsys) | os | writes to disk | Go 1.23, copies an FS to a directory |
Fix / how to use it: accept an fs.FS (or the smallest interface you need) in your function signature and test it on a MapFS:
// Package fsabs writes file code against fs.FS so the same function runs on
// the disk, on an embedded tree and on an in-memory test tree.
package fsabs
import (
"bufio"
"io/fs"
"path"
"strings"
)
// CountLines returns the number of lines of every .txt file under fsys.
// Names inside fs.FS are always slash-separated and never start with "/".
func CountLines(fsys fs.FS) (map[string]int, error) {
out := map[string]int{}
err := fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || path.Ext(p) != ".txt" {
return nil
}
f, err := fsys.Open(p)
if err != nil {
return err
}
defer f.Close()
n := 0
sc := bufio.NewScanner(f)
for sc.Scan() {
n++
}
out[p] = n
return sc.Err()
})
return out, err
}
// Greeting reads one file with fs.ReadFile, which uses the FS's own
// ReadFile method when it has one (embed.FS and os.DirFS do).
func Greeting(fsys fs.FS) (string, error) {
b, err := fs.ReadFile(fsys, "greeting.txt")
return strings.TrimSpace(string(b)), err
}
// Section narrows an FS to one subtree: fs.Sub does not copy anything.
func Section(fsys fs.FS, dir string) (fs.FS, error) {
return fs.Sub(fsys, dir)
}embed: files inside the binary Must-know
In plain words: //go:embed copies files into your compiled program, so the binary carries its own templates, SQL migrations, static assets or default config and works without any files next to it.
Common misunderstanding: "I can embed any path, including ../shared/x.txt or a symlink, and embedded files update when I change them on disk." Patterns are relative to the package directory and may not contain ..; symbolic links are rejected; and the content is frozen when you run go build.
Definition: a directive //go:embed pattern... immediately above a package-level variable of type string, []byte or embed.FS. Patterns use path.Match rules, are relative to the package directory and use / even on Windows. A directory pattern embeds the whole tree except names beginning with . or _; the all: prefix includes them. static/* embeds .hidden files that static does not. Only the first-level match differs, deeper dotfiles still need all:. Patterns must match at least one file, must not match files outside the module (including .git, vendor, directories holding a go.mod), symlinks, or names with special characters. A string or []byte takes exactly one file. import "embed" is required, with _ "embed" when you only use string or []byte. embed.FS has Open, ReadFile, ReadDir and implements fs.FS; embedded files have a zero modification time, so http.FileServer sends no Last-Modified header.
step moment what happens
1 go build the go command resolves the patterns, fails the build on a bad or empty match
2 link file bytes are placed in the read-only data of the executable
3 run time embed.FS reads straight from that data: no disk, no os.Open, cannot fail with ENOENT
4 deploy edit a file on disk: the running binary still serves the old bytes until rebuiltReal scenarios: a single-binary admin UI served with http.FileServer(http.FS(sub)); HTML templates parsed at start-up with template.ParseFS; SQL migrations bundled with the service; a default config used when no file is given; a license text printed by --version.
| Variable type | Patterns allowed | Result | Typical use |
|---|---|---|---|
string | exactly one file | contents as text | version file, one template |
[]byte | exactly one file | contents as bytes | icon, certificate |
embed.FS | many files and directories | read-only tree | static assets, migrations |
| Build error (real, Go 1.27 toolchain) | Cause |
|---|---|
pattern ../secret.txt: invalid pattern syntax | .. is not allowed |
pattern nothing*.txt: no matching files found | every pattern needs a match |
pattern link.txt: cannot embed irregular file link.txt | symlinks are rejected |
misplaced go:embed directive | directive not directly above a variable |
invalid go:embed: multiple files for type string | two files into a string |
Fix / how to use it: embed the directory, strip the prefix with fs.Sub, serve it with http.FS. The tests show which files each form includes and that missing files give 404:
// Package embedsite serves a static site compiled into the binary.
package embedsite
import (
"embed"
"io/fs"
"net/http"
)
// Version is a single file embedded into a string.
//
//go:embed VERSION
var Version string
// Page is a single file embedded into a byte slice.
//
//go:embed static/index.html
var Page []byte
// Static holds the whole tree. Naming the directory skips names that begin
// with "." or "_"; "all:" would include them.
//
//go:embed static
var static embed.FS
// Hidden shows the all: prefix: dotfiles and underscore files are included.
//
//go:embed all:static
var Hidden embed.FS
// Handler serves the embedded tree. fs.Sub strips the "static" prefix, so the
// URL /css/app.css maps to the embedded file static/css/app.css.
func Handler() (http.Handler, error) {
sub, err := fs.Sub(static, "static")
if err != nil {
return nil, err
}
return http.FileServer(http.FS(sub)), nil
}
// Files returns the names of the embedded files (without all:).
func Files() ([]string, error) {
var out []string
err := fs.WalkDir(static, ".", func(p string, d fs.DirEntry, err error) error {
if err == nil && !d.IsDir() {
out = append(out, p)
}
return err
})
return out, err
}During development you want the opposite: files reread from disk without a rebuild. Hide the choice behind fs.FS: use os.DirFS("static") when an environment variable is set and the embedded fs.Sub otherwise.
Temp files and directories Must-know
In plain words: a temp file is a uniquely named scratch file that nobody else is using. Go creates the name for you, makes it private and leaves deleting it to you (or to the test framework in tests).
Common misunderstanding: "Temp files are cleaned up automatically." os.CreateTemp and os.MkdirTemp never remove anything. Only t.TempDir() registers cleanup, and only for the duration of the test.
Definition: os.CreateTemp(dir, pattern) creates a file opened O_RDWR|O_CREATE|O_EXCL with mode 0o600 before umask; the random string replaces the last * in the pattern or is appended; a pattern containing a path separator fails with pattern contains path separator. If dir is empty it uses os.TempDir() ($TMPDIR or /tmp on Unix). os.MkdirTemp(dir, pattern) does the same for a directory with mode 0o700. Names are unique even across concurrent goroutines and processes because of O_EXCL. t.TempDir() (Go 1.15) returns a fresh directory per call and removes it when the test and its subtests finish; t.Setenv and t.Cleanup pair with it.
step call result
1 os.CreateTemp("", "job-*.json") /tmp/job-3857125602.json (opened, 0600)
2 f.Write(...), f.Close()
3 process(f.Name())
4 os.Remove(f.Name()) your job; defer it right after step 1
5 t.TempDir() cleaned automatically when the test endsReal scenarios: unzipping an upload to a scratch directory before validation; a sort step spilling to disk; an atomic write staging file (it must be in the same directory as the target, not in /tmp); a golden-file test; a CLI that renders a diff to a temp file and opens an editor.
| Need | Use | Cleanup |
|---|---|---|
| Scratch file in production | os.CreateTemp(dir, "x-*") | defer os.Remove(f.Name()) |
| Scratch directory | os.MkdirTemp(dir, "x-") | defer os.RemoveAll(path) |
| File in a test | filepath.Join(t.TempDir(), "x") | automatic |
| Staging file for a rename | os.CreateTemp(filepath.Dir(target), ...) | rename or remove on error |
| Default directory | os.TempDir() | may be tmpfs (RAM) in containers |
Fix / how to use it: pair creation and removal on adjacent lines, and keep staging files next to their destination:
// Package tempdemo shows os.CreateTemp, os.MkdirTemp and cleanup rules.
package tempdemo
import (
"os"
)
// Process writes work data to a private temp file, runs fn and always
// removes the file. CreateTemp opens it O_RDWR|O_CREATE|O_EXCL with mode 0600
// and replaces the last "*" in the pattern with random digits.
func Process(dir string, data []byte, fn func(path string) error) (err error) {
f, err := os.CreateTemp(dir, "job-*.json")
if err != nil {
return err
}
defer os.Remove(f.Name()) // the file is not removed for you
if _, err = f.Write(data); err != nil {
f.Close()
return err
}
if err = f.Close(); err != nil {
return err
}
return fn(f.Name())
}
// Scratch returns a fresh private directory and its cleanup function.
// os.MkdirTemp creates it with mode 0700.
func Scratch(dir, pattern string) (path string, cleanup func() error, err error) {
path, err = os.MkdirTemp(dir, pattern)
if err != nil {
return "", nil, err
}
return path, func() error { return os.RemoveAll(path) }, nil
}bufio: Reader, Writer and Scanner Must-know
In plain words: bufio puts a buffer between your code and the file. Reading a line at a time from a raw file would be one system call per few bytes; bufio reads 4 KiB (or more) at once and hands you pieces. Writing works the other way: small writes pile up and go out together.
Common misunderstanding: "bufio.Scanner is how you read a text file." It is, until a line is longer than 64 KiB. Then Scan returns false, the loop ends as if the file had ended, and the only trace is sc.Err() returning bufio.Scanner: token too long. Minified JSON, a CSV cell with embedded data and one-line log records hit this in production.
Definition:
bufio.NewReader(r)(default 4096-byte buffer;NewReaderSizefor others) offersReadString(delim)andReadBytes(delim)(return the data including the delimiter, together withio.EOFfor a last line without one),ReadLine(low level, returnsisPrefixfor long lines; the documentation steers you toReadStringor aScanner),ReadRune,Peek,Discard. There is no maximum line length; memory grows with the line.bufio.NewScanner(r)reads tokens with aSplitFunc:ScanLines(default; strips\nand a preceding\r),ScanWords,ScanRunes,ScanBytes, or your own. The default maximum token isbufio.MaxScanTokenSize, 64 KiB;Scanner.Buffer(buf, max)raises it (call it before the firstScan). When a token is too long,Scanstops andErr()returnsbufio.ErrTooLong. A split function that returns empty tokens without progress panics withbufio.Scan: too many empty tokens without progressing.bufio.NewWriter(w)(default 4096 bytes;NewWriterSize) collects writes;Flushsends the rest. After the first write error the Writer is sticky: every later write andFlushreturn that error, so one check atFlushis enough.
step code effect
1 bw := bufio.NewWriter(f) 4096-byte buffer, nothing written to f
2 bw.WriteString("a\n") (x 1000) bytes stay in memory; a write(2) happens each time the buffer fills
3 (process exits here without Flush) the last partial buffer is lost
4 bw.Flush() remaining bytes go to f; returns the first error seen
5 f.Sync(); f.Close() flushing bufio is not flushing the diskReal scenarios: a log processor reading a 20 GiB access log line by line; a CSV exporter writing one million rows; a protocol parser reading \r\n-terminated commands from a net.Conn; a word counter (ScanWords); reading NDJSON where some lines reach several megabytes; a CLI reading a password prompt from os.Stdin.
| Task | Use | Limit or cost |
|---|---|---|
| Lines up to a known maximum | Scanner with Buffer(make([]byte, 0, 64*1024), 1<<20) | fails with ErrTooLong above the maximum |
| Lines of unknown length | Reader.ReadString('\n') | memory grows with the line; add your own cap |
| Binary framing | io.ReadFull and encoding/binary | see io package |
| Many small writes | bufio.Writer, one Flush at the end | forgetting Flush loses data |
| Word or rune tokens | Scanner with ScanWords or ScanRunes | same 64 KiB token cap |
| Custom delimiter | Scanner.Split(func) | return (0, nil, nil) to ask for more data |
| Peek without consuming | Reader.Peek(n) | n must not exceed the buffer size |
Fix / how to use it: the snippet reproduces the failure with a 64 KiB + 1 line, shows three ways around it, and proves Flush is needed:
// Package scan shows bufio.Scanner limits, bufio.Reader for unbounded lines,
// custom split functions and bufio.Writer flush rules.
package scan
import (
"bufio"
"bytes"
"errors"
"io"
"strings"
)
// Lines uses the default Scanner: tokens up to bufio.MaxScanTokenSize (64 KiB).
// A longer line stops the scan with bufio.ErrTooLong.
func Lines(r io.Reader) ([]string, error) {
var out []string
sc := bufio.NewScanner(r)
for sc.Scan() {
out = append(out, sc.Text())
}
return out, sc.Err() // always check Err after the loop
}
// LinesMax raises the limit with Scanner.Buffer. The buffer starts at 4 KiB
// and may grow up to max bytes.
func LinesMax(r io.Reader, max int) ([]string, error) {
var out []string
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 0, 4096), max)
for sc.Scan() {
out = append(out, sc.Text())
}
return out, sc.Err()
}
// LinesUnbounded reads lines of any length with bufio.Reader.ReadString.
// The last line may have no trailing newline and arrives together with io.EOF.
func LinesUnbounded(r io.Reader) ([]string, error) {
br := bufio.NewReader(r)
var out []string
for {
line, err := br.ReadString('\n')
if len(line) > 0 {
out = append(out, strings.TrimRight(line, "\r\n"))
}
if errors.Is(err, io.EOF) {
return out, nil
}
if err != nil {
return out, err
}
}
}
// Words counts whitespace separated words with the ScanWords split function.
func Words(r io.Reader) (int, error) {
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
n := 0
for sc.Scan() {
n++
}
return n, sc.Err()
}
// SplitComma is a custom SplitFunc: tokens are separated by commas.
func SplitComma(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, ','); i >= 0 {
return i + 1, data[:i], nil
}
if atEOF {
return len(data), data, nil // final token without a comma
}
return 0, nil, nil // ask for more data
}
// Buffered writes through a bufio.Writer. Nothing reaches w until the buffer
// fills or Flush is called, and Flush returns the first write error.
func Buffered(w io.Writer, lines []string) error {
bw := bufio.NewWriter(w)
for _, l := range lines {
if _, err := bw.WriteString(l + "\n"); err != nil {
return err
}
}
return bw.Flush()
}Atomic writes, fsync and durability Must-know
In plain words: to replace a file so that readers and crashes only ever see "old" or "new", write the new content to a temporary file next to it, force it to disk, then rename it over the original.
Common misunderstanding: "os.Rename makes the write durable." Rename is atomic with respect to other processes, but it does not push the file's data to the disk. Without an fsync of the temp file first, a power cut can leave the new name pointing at a file whose blocks were never written (zero length is the classic result).
Definition: a successful write means the kernel accepted the bytes into the page cache. (*os.File).Sync calls fsync (on macOS Go uses F_FULLFSYNC, because plain fsync there "doesn't fully flush contents to disk", per the comment in internal/poll/fd_fsync_darwin.go). A rename is a change to the directory, which is itself a file, so for the rename to survive a crash you fsync the directory too. Rename is atomic only inside one file system: across file systems it fails with EXDEV (invalid cross-device link), which is why the temp file lives in the target's directory and not in /tmp. The recipe is the same one databases and package managers use; what a database adds on top (a write-ahead log, group commit, checksums) is in Durability, WAL & Crash Recovery.
step action crash here leaves
1 CreateTemp(dir, "config.json.tmp-*") old config.json, stray temp file
2 write bytes, Chmod(perm) old config.json, stray temp file
3 tmp.Sync() old config.json, durable temp file
4 tmp.Close() same
5 os.Rename(tmp, "config.json") old or new, never a mix
6 fsync(directory) new, and the rename is durableReal scenarios: an application config rewritten by an admin UI; a JSON state file; a download that must appear in its final name only when complete; a cache index; a deployment symlink swapped with rename; git, dpkg and editors use the same pattern.
| Method | Atomic for readers | Survives power loss | Cost |
|---|---|---|---|
os.WriteFile in place | no (truncates first) | no | one syscall sequence |
Temp file and Rename, no Sync | yes | no (may be empty after a crash) | cheap |
Temp file, Sync, Rename | yes | data yes, rename maybe | one fsync |
Temp file, Sync, Rename, directory Sync | yes | yes (on a file system that honours fsync) | two fsyncs, milliseconds each |
| Append-only log plus checkpoint | yes | yes | design cost; this is what databases do |
O_SYNC/O_DSYNC on every write | per write | per write | slowest |
Fix / how to use it: the helper below implements the recipe, cleans up its temp file on every error path and is tested against a concurrent reader that must never see a partial file:
// Package atomicwrite replaces a file so that readers see either the old
// content or the new content, never a half-written file.
package atomicwrite
import (
"io/fs"
"os"
"path/filepath"
)
// WriteFile writes data to path atomically on POSIX file systems:
// temp file in the same directory, fsync, rename, fsync of the directory.
func WriteFile(path string, data []byte, perm fs.FileMode) (err error) {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*")
if err != nil {
return err
}
tmpName := tmp.Name()
defer func() {
if err != nil {
tmp.Close() // second Close returns an error we ignore
os.Remove(tmpName)
}
}()
if _, err = tmp.Write(data); err != nil {
return err
}
if err = tmp.Chmod(perm); err != nil { // CreateTemp uses 0600
return err
}
if err = tmp.Sync(); err != nil { // data on disk before the name flips
return err
}
if err = tmp.Close(); err != nil {
return err
}
if err = os.Rename(tmpName, path); err != nil { // atomic replace
return err
}
return syncDir(dir) // make the rename itself durable
}
func syncDir(dir string) error {
d, err := os.Open(dir)
if err != nil {
return err
}
defer d.Close()
return d.Sync()
}Limits you must know: Sync returns when the operating system says the data is stable, and a consumer disk with a volatile write cache or a network file system may still lie; on Windows Rename over an existing file is not guaranteed atomic and fails when the target is open; and the directory Sync is not supported on Windows (a directory handle cannot be flushed that way), so ignore that step there.
Locking and O_EXCL Important
In plain words: when two processes must not work on the same thing, they can agree to use a file as a flag. Creating a file only if it does not exist is an operation the kernel does in one step, so exactly one process wins.
Common misunderstanding: "A lock file is a lock." It is a convention. Nothing stops a process that ignores it, and if the owner crashes the file stays behind, so the next start-up sees a lock nobody holds.
Definition: O_CREATE|O_EXCL fails with fs.ErrExist if the name exists; check and create are one atomic operation in the kernel. A lock file therefore needs: the pid inside (so a human or a supervisor can judge staleness), removal on clean exit (defer, plus a signal handler, see OS Processes, Signals & Graceful Shutdown), and a policy for stale files. A better primitive on Unix is flock(2) through syscall.Flock: the kernel drops the lock when the process dies, so there is no stale state. flock is advisory, per open file description, and its behaviour on NFS depends on the mount; Windows needs LockFileEx (through golang.org/x/sys/windows). Go's standard library does not provide a portable lock API.
step process A process B file "app.lock"
1 OpenFile(O_CREATE|O_EXCL) ok created
2 OpenFile(O_CREATE|O_EXCL) error: file exists (ErrLocked)
3 write pid, work ...
4 crash (SIGKILL) stays, owner gone
5 OpenFile(O_CREATE|O_EXCL) error: file exists (stale lock)
6 flock variant: process dies -> the kernel drops the lock -> B's flock succeedsReal scenarios: a cron job that must not overlap with its previous run; a single-instance desktop or CLI tool; a migration command that must run once; a cache warmer shared by several workers on one host; exclusive creation of an output file named by a content hash.
| Technique | Cleans up after a crash | Cross-platform | Works across hosts |
|---|---|---|---|
O_EXCL lock file | no (stale file) | yes | only where the shared file system honours O_EXCL |
flock on a held file | yes | Unix only | NFS-dependent |
LockFileEx | yes | Windows only | no |
| Database advisory lock or row lock | yes (connection closes) | yes | yes, see Locks & Concurrency Control |
| Lease in etcd, Redis or a database | yes (TTL) | yes | yes |
Fix / how to use it: Lock in the first snippet (openflags.go) takes a pid-stamped exclusive file and returns the unlock function; use it for single-host jobs and a database or lease lock when more than one host is involved.
Large files: stream, do not load Important
In plain words: a program that handles big files in constant memory never holds the whole file: it reads a piece, handles it, forgets it.
Common misunderstanding: "os.ReadFile is fine, memory is cheap." It allocates the whole file, doubles it if you convert to string, and a few concurrent requests turn a 500 MB upload endpoint into an out-of-memory kill.
Definition: io.Copy(dst, src) moves bytes with a 32 KiB buffer, and uses WriterTo or ReaderFrom shortcuts when available (on Linux, copying between files or from a file to a socket can use copy_file_range or sendfile inside the kernel). io.CopyN and io.LimitReader cap the size. io.NewSectionReader(r io.ReaderAt, off, n) exposes a window of a file as a Reader, ReaderAt and Seeker, which is how HTTP range requests (http.ServeContent takes an io.ReadSeeker) and parallel chunk downloads work. bufio.Reader.ReadLine and ReadString read lines without a cap. For structured formats use streaming decoders: csv.Reader.Read, json.Decoder.Decode one value at a time (see JSON, XML, Struct Tags, Encoder/Decoder, Base64). Memory-mapping (syscall.Mmap) is possible but outside this page.
step call memory
1 f := os.Open(big) a few hundred bytes
2 io.Copy(w, f) one 32 KiB buffer reused
3 io.Copy(w, io.LimitReader(f, 10<<20)) same, capped at 10 MiB
4 sr := io.NewSectionReader(f, off, n); io.Copy(w, sr) only [off, off+n) is read
5 os.ReadFile(big) len(file) bytes on the heapReal scenarios: a download endpoint that streams from disk to the client with http.ServeContent; checksumming a backup; resumable uploads that write chunks with WriteAt; extracting the last megabyte of a log (Seek from the end); counting lines in a 30 GiB export.
| Pattern | Memory | Seekable | Use |
|---|---|---|---|
os.ReadFile | whole file | n/a | small config and fixtures |
io.Copy | 32 KiB | no | copy and upload |
io.SectionReader | window only | yes | range requests, chunks |
bufio.Reader.ReadLine | buffer size | no | very long lines |
Seek(-n, io.SeekEnd) | n bytes | yes | tail of a file |
mmap | page cache | yes | databases, read-mostly indexes |
Fix / how to use it: the tests measure allocations during a 64 MiB copy (it stays under 8 MiB), read a 12-byte window from the middle, and count lines when one line is 5 MiB:
// Package bigfile streams large files with constant memory.
package bigfile
import (
"bufio"
"errors"
"io"
"os"
)
// Copy streams src to dst using io.Copy; memory use is one 32 KiB buffer.
// When both ends are *os.File on Linux, io.Copy can use copy_file_range or
// sendfile and skip user space entirely.
func Copy(dst, src string) (n int64, err error) {
in, err := os.Open(src)
if err != nil {
return 0, err
}
defer in.Close()
out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return 0, err
}
defer func() {
if cerr := out.Close(); err == nil {
err = cerr
}
}()
return io.Copy(out, in)
}
// Range returns length bytes starting at off, without reading the rest.
// io.SectionReader gives a Reader, ReaderAt and Seeker view of a window.
func Range(f io.ReaderAt, off, length int64) ([]byte, error) {
sr := io.NewSectionReader(f, off, length)
return io.ReadAll(sr)
}
// CountLines counts newlines in constant memory, however long the lines are.
func CountLines(r io.Reader) (int, error) {
br := bufio.NewReaderSize(r, 64<<10)
n := 0
for {
_, isPrefix, err := br.ReadLine()
if errors.Is(err, io.EOF) {
return n, nil
}
if err != nil {
return n, err
}
if !isPrefix {
n++
}
}
}
// Tail returns the last n bytes of a file by seeking from the end.
func Tail(path string, n int64) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return nil, err
}
off := fi.Size() - n
if off < 0 {
off = 0
}
if _, err := f.Seek(off, io.SeekStart); err != nil {
return nil, err
}
return io.ReadAll(f)
}Watching files for changes Good to know
In plain words: instead of re-reading a config every second, you can ask the operating system to tell you when a file changes.
Common misunderstanding: "Watch the file itself." Many editors and deploy tools replace a file by writing a new one and renaming it over the old, which removes the watched inode. The fsnotify project says exactly this: watch the parent directory and filter events by name.
Definition: the standard library has no watcher. github.com/fsnotify/fsnotify wraps inotify (Linux), kqueue (BSD and macOS) and ReadDirectoryChangesW (Windows). It reports Create, Write, Remove, Rename and Chmod events on a directory and does not recurse by itself; a watch is lost when the directory moves; Linux limits watches per user with fs.inotify.max_user_watches; on kqueue every watched file costs a file descriptor. Events can arrive in bursts (one save may give several Write events), so debounce before reloading. Kubernetes mounts a ConfigMap as symlinks swapped atomically, which makes the "watch the parent directory" rule mandatory there.
step event on /etc/app/ what the program should do
1 Create config.json.tmp-1 ignore (name does not match)
2 Write config.json.tmp-1 ignore
3 Rename config.json.tmp-1 -> config.json Create event for config.json: start a 100 ms debounce timer
4 Write config.json (second event) reset the timer
5 timer fires reload, validate, swap the new config in; keep the old one on errorReal scenarios: hot reload of TLS certificates and config; a dev server restarting on source changes; a sync agent noticing new files; a log-tailing tool noticing rotation. For production config, a periodic Stat poll (compare ModTime and Size) or a signal such as SIGHUP is often simpler and more portable.
| Mechanism | Latency | Platform support | Failure mode |
|---|---|---|---|
fsnotify | milliseconds | Linux, BSD, macOS, Windows | lost watches, limits, network file systems |
Poll Stat every N seconds | N seconds | everywhere | misses nothing, costs a syscall per tick |
SIGHUP to reload | immediate | Unix | needs an operator or a supervisor |
| Content hash compare on a timer | N seconds | everywhere | cost grows with file size |
Fix / how to use it: keep the reload function pure (parse and validate into a new value, then swap with one atomic pointer store), so it is safe whichever mechanism triggers it.
Windows differences Good to know
In plain words: the Go API is the same on Windows, but the file system underneath has other rules, and code that only ran on Linux or macOS can fail there.
Common misunderstanding: "filepath hides every difference." It hides the separator. It does not hide reserved names, case-insensitive matching, locking of open files or the missing atomic rename.
Definition: the separator is \ (and / is accepted by most APIs); filepath.IsAbs("\foo") reports false because the path is relative to the current drive (the Go blog uses this example), and volumes (C:) exist. Reserved names such as NUL, CON, COM1 refer to devices, which is why IsLocal rejects them. File names are case-insensitive but case-preserving by default. A file that another process has open usually cannot be deleted or renamed over (a sharing violation), and os.Rename is documented as not atomic on non-Unix platforms. Symlinks need a privilege or developer mode. \r\n line endings: Scanner with ScanLines strips the \r. Permission bits are mostly emulated: only the read-only attribute maps to 0o444 against 0o666.
| Topic | Linux and macOS | Windows |
|---|---|---|
| Separator | / | \ (/ also accepted) |
| Rename over an existing file | atomic | not atomic; fails if the target is open |
| Delete an open file | allowed (inode lives until closed) | usually refused |
| Case | sensitive on Linux; insensitive by default on macOS | insensitive |
| Reserved names | none | NUL, CON, PRN, AUX, COM1 ... |
| Permission bits | full | read-only flag only |
Directory fsync | works | not meaningful |
| Symlinks | normal | privilege or developer mode |
Fix / how to use it: use filepath and Localize, never concatenate with "/" or "\\", run your tests on a Windows runner if you ship there, and do not rely on deleting a file that may still be open.
Mechanics
Error texts you will see Must-know
Failures from os are *fs.PathError (Op, Path, Err) or *os.LinkError for Rename, Link and Symlink. The Err is a syscall.Errno whose text depends on the operating system. Test with errors.Is, never by comparing strings.
| Message (real unless marked) | Test with | Cause |
|---|---|---|
open missing.txt: no such file or directory | errors.Is(err, fs.ErrNotExist) | path absent or a parent missing |
open f: file exists | errors.Is(err, fs.ErrExist) | O_EXCL on an existing name |
open ro: permission denied | errors.Is(err, fs.ErrPermission) | mode or ownership forbids it |
read d: is a directory | errors.Is(err, syscall.EISDIR) | reading a directory as a file |
remove d: directory not empty | errors.Is(err, syscall.ENOTEMPTY) | Remove on a non-empty directory |
rename f d: file exists (macOS; Linux says is a directory) | errors.As(err, &linkErr) | target is a directory |
write closed: file already closed | errors.Is(err, os.ErrClosed) | use after Close |
write f: bad file descriptor | errors.Is(err, syscall.EBADF) | writing a read-only file |
openat ../f: path escapes from parent | match os.ErrInvalid-style text | os.Root refused the name |
bufio.Scanner: token too long | errors.Is(err, bufio.ErrTooLong) | line over the Scanner limit |
rename a b: invalid cross-device link (Linux, expected, not run) | errors.Is(err, syscall.EXDEV) | rename across file systems |
open x: too many open files (expected, not run) | errors.Is(err, syscall.EMFILE) | descriptor limit (ulimit -n) reached |
write x: no space left on device (expected, not run) | errors.Is(err, syscall.ENOSPC) | disk or quota full; may appear only at Close |
pattern ../secret.txt: invalid pattern syntax (build) | n/a | go:embed with .. |
pattern nothing*.txt: no matching files found (build) | n/a | go:embed matched nothing |
Version gates, in one table Must-know
| Feature | Needs | If your go.mod is older |
|---|---|---|
os.ReadFile, os.WriteFile, os.CreateTemp, os.MkdirTemp, os.ReadDir, io/fs, embed | Go 1.16 | use io/ioutil equivalents; no embed |
t.TempDir | Go 1.15 | use os.MkdirTemp and t.Cleanup |
filepath.IsLocal, filepath.SkipAll | Go 1.20 | write the checks by hand |
filepath.Localize, os.CopyFS | Go 1.23 | use IsLocal after FromSlash |
os.Root, os.OpenRoot, os.OpenInRoot, Root.FS | Go 1.24 | use IsLocal and accept the symlink gap |
fs.ReadLinkFS, Root.ReadFile/WriteFile/MkdirAll/RemoveAll/Rename | Go 1.25 | use Root.Open and copy |
From a call to the kernel
| Go call | Typical system call (Linux) | Notes |
|---|---|---|
os.Open, os.OpenFile | openat | returns a file descriptor; O_CLOEXEC is added so children do not inherit it |
f.Read, f.Write | read, write | one call per Read; hence bufio |
f.ReadAt, f.WriteAt | pread, pwrite | do not move the shared offset |
f.Seek | lseek | |
f.Sync | fsync | macOS: fcntl(F_FULLFSYNC) |
f.Close | close | can return a delayed error |
os.Stat, os.Lstat | fstatat | follows or does not follow a link |
os.ReadDir | getdents64 | reads in batches, sorts in user space |
os.Rename | renameat | atomic in one file system |
os.Remove | unlinkat | tries file then directory |
os.Root methods | the openat family, relative to the root's directory descriptor | per the Go blog; tracks the directory across renames |
Descriptors are a per-process limit (ulimit -n, commonly 1024 soft by default on Linux shells); a leak of unclosed files turns into too many open files. Go's runtime also attaches a finalizer-like cleanup to *os.File, so an unreachable file is eventually closed, but never rely on that for timing.
Tools that watch your file code
| Tool | What it catches |
|---|---|
go vet | printf mistakes and copied locks; it does not flag defer inside a loop, a reviewer must |
errcheck through golangci-lint (see Project Layout, Linting & Build) | ignored errors from Close, Flush, Remove |
go test -race | races on your own shared buffers; two goroutines calling Read on one *os.File are not a Go data race but still interleave the bytes |
lsof -p PID and ls /proc/PID/fd | leaked descriptors (expected, not run) |
strace -f -e trace=file,fsync | exactly which syscalls your code makes (expected, not run) |
fstest.TestFS | an fs.FS that breaks the contract |
Solving the classic problems
| Problem | Solution | Why it works | Cost or limit |
|---|---|---|---|
| Config rewritten while read | temp file, Sync, Rename | readers see old or new | same directory, needs write access to it |
| Untrusted file name | IsLocal then os.Root | lexical check plus kernel confinement | Go 1.24, mount points not limited |
| Lines longer than 64 KiB | Scanner.Buffer with a cap, or ReadString | explicit limit or none | memory grows with the line |
| Output missing its tail | defer bw.Flush() and check its error | buffer emptied | forgetting it is silent |
| Two instances of a job | O_EXCL lock file or flock | kernel check-and-create | stale files, host-local |
| Tests need files | t.TempDir() or fstest.MapFS | cleanup and no disk | MapFS is not a real disk |
| Ship templates and assets | //go:embed, fs.Sub, http.FS | single binary | rebuild to change |
| Huge file in constant memory | io.Copy, SectionReader, streaming decoders | one buffer | no random access in io.Copy |
| Directory walk skipping junk | WalkDir and SkipDir | prunes subtrees cheaply | does not follow symlinks |
| Cleanup of old files | WalkDir, check d.Info().ModTime(), Remove | one pass | race with writers; delete by name only |
An upload store that keeps metadata honest
Upload handlers have two jobs that fail separately: the bytes on disk and the row in the database. Write the bytes to a temp file in the target directory, Sync, rename it to a content-addressed name (the SHA-256 of the content), then insert the row. If the process dies between rename and insert, the file is an orphan that a periodic sweep can delete; if it dies before the rename, only a temp file is left. Never insert the row first: a row pointing at a missing file is a user-visible error.
-- the metadata that goes with the file; the unique key makes a re-upload of the same content idempotent
CREATE TABLE stored_files (
sha256 char(64) PRIMARY KEY,
size_bytes bigint NOT NULL CHECK (size_bytes >= 0),
mime_type text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
-- sweep: orphans are files on disk without a row, found by comparing a directory listing with this query
SELECT sha256 FROM stored_files ORDER BY sha256;Testing file code
Use t.TempDir() for anything touching the disk, fstest.MapFS for pure read logic, and an injected io.Writer where the function only needs to write. Test the unhappy paths directly: fs.ErrExist from O_EXCL, ErrTooLong from a 64 KiB + 1 line, a rename onto a directory, a symlink that escapes. Each snippet in this chapter has such a test and passes go test -race.
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Read a small config at start-up | os.ReadFile | fs.ReadFile if the source may be embedded | simple, bounded |
| Replace a config or state file | atomic write helper | directory Sync if durability matters | no partial file |
| Read a big text file | bufio.Scanner with Buffer | handle sc.Err() | line-at-a-time, bounded memory |
| Lines of unknown size | bufio.Reader.ReadString | cap the total | no token limit |
| Write many small records | bufio.Writer | defer Flush and check the error | fewer syscalls |
| Serve static assets | embed.FS, fs.Sub, http.FS | os.DirFS in development | one binary |
| Name comes from a user | IsLocal then os.Root | a store keyed by hash, not by name | traversal and symlink safety |
| Read-only logic under test | accept fs.FS | fstest.MapFS | no disk, fast |
| Scratch data | os.CreateTemp / MkdirTemp | defer removal | private and unique |
| One job at a time on a host | flock or O_EXCL lock | pid in the file | cheap |
| One job at a time in a cluster | database or lease lock | fencing token | files do not span hosts |
| React to file changes | fsnotify on the directory | debounce and validate | low latency |
| Copy a big file | io.Copy | copy_file_range path via *os.File | constant memory |
| Share files between services | object storage, not a shared disk | presigned URLs | see Object Storage, Distributed File Systems, Presigned URLs & Content-Addressable Storage |
In architecture: from a single process to a distributed system
A file is local state: it belongs to one machine and one file system. Every step toward many machines is a decision about where that state goes.
Monolith: one process, one database
One server, one disk. Uploads go to /var/lib/app/uploads/<sha256>, config is /etc/app/config.json, logs go to stdout. The simple correct usage is this page: atomic writes for state files, os.Root for any name from a request, embed for templates and migrations, t.TempDir() for tests, Close errors handled. A PHP/Laravel monolith keeps the same files under storage/app and storage/logs, and a php artisan storage:link symlink exposes public files; Go has no framework doing that, so the traversal rules above are yours to enforce.
Modular monolith and multiple databases
Modules own directories the way they own tables: uploads/ belongs to the media module, exports/ to reporting. Give each module an os.Root (or a base directory plus IsLocal) so a bug in one cannot write into another's tree, and expose storage through an interface (Put, Get, Delete over fs.FS for reading) so the module can move to object storage without callers noticing. A shared scratch directory needs unique names from CreateTemp, never fixed names.
Microservices
Local files do not cross a service boundary. Containers get a fresh writable layer on every start, replicas do not see each other's disks, and a rolling deploy replaces the pod that held your upload. Store durable files in object storage and keep only metadata (the stored_files row) in the service database; pass references (keys, presigned URLs) between services, never paths; see File Uploads, S3 & Serving from a CDN. Use embed for what ships with the image, ConfigMaps or secret mounts for config (watch the parent directory, mounts are symlink swaps), and an emptyDir or tmpfs for scratch space with a size limit. The temp directory in a container may be RAM-backed, so a big CreateTemp file counts against the memory limit.
Distributed data: replicas, caches, NAT and containers
A network file system (NFS, EFS, CephFS, SMB) looks like a local directory and breaks local assumptions: O_EXCL and flock may not be reliable, rename may not be atomic for readers on other hosts, directory listings can be stale (attribute caching), and fsync costs a network round trip. Treat shared file systems as eventually consistent storage and prefer an append-only, content-addressed layout (write once under a unique name, never overwrite). A replicated database gives you the transaction and durability guarantees a file cannot; when you need "write this and be sure", use the database or a log, see Storage Engines: B-tree vs LSM-tree and Durability, WAL & Crash Recovery. A CDN or cache in front of file serving needs correct validators: embedded files have no Last-Modified, so serve an ETag or fingerprinted names.
Scaling path: 1×, 10×, 100×
| Scale | File concern | Action |
|---|---|---|
| 1x (one process) | correctness: Close, Flush, partial writes, traversal | atomic writes, os.Root, tests with t.TempDir() |
| 10x (one busy host) | descriptors, page cache, fsync latency, directory with millions of entries | raise ulimit -n, shard directories by hash prefix (ab/cd/abcdef...), batch Sync, stream with io.Copy |
| 100x (many hosts) | local disks diverge, NFS surprises, large objects | object storage, content-addressed keys, presigned uploads, a CDN, metadata in the database |
| any | untrusted names, hostile archives | os.Root, size limits, LimitReader, extract into a scratch root and validate |
For PHP/Laravel developers
PHP's file functions are close relatives, with different defaults.
| PHP | Go | Difference |
|---|---|---|
file_get_contents($p) | os.ReadFile(p) | Go returns an error value and never false; both load everything |
file_put_contents($p, $d) | os.WriteFile(p, d, 0o644) | PHP LOCK_EX locks while writing; neither is atomic |
file_put_contents($p, $d, FILE_APPEND) | OpenFile(p, O_APPEND, ...) and Write | Go makes the flag explicit |
fopen($p, 'r') | os.Open(p) | mode letters become flags |
fopen($p, 'w') | os.Create(p) | both truncate |
fopen($p, 'x') | OpenFile(p, O_CREATE+O_EXCL, perm) | exclusive creation |
fopen($p, 'a') | OpenFile(p, O_APPEND+O_CREATE+O_WRONLY, perm) | |
fgets($h) / SplFileObject iteration | bufio.Scanner or Reader.ReadString | PHP fgets has no 64 KiB cap; Go Scanner does |
fclose($h) | f.Close() | fclose returns a bool you rarely check; Go returns the error that matters |
tempnam(), tmpfile() | os.CreateTemp | Go creates with 0600 and exclusive create |
realpath() | filepath.EvalSymlinks plus Abs | |
glob() | filepath.Glob | no ** in either, Go has no GLOB_BRACE |
Storage::disk('local')->put() | your own wrapper over fs.FS and os.Root | no abstraction layer is built in |
// PHP: the 'w' mode truncates immediately, so this is not atomic either
file_put_contents($path, $json, LOCK_EX);
// the PHP version of the same recipe: temp file then rename
$tmp = tempnam(dirname($path), 'cfg');
file_put_contents($tmp, $json);
rename($tmp, $path); // atomic on the same file system, but no fsync unless you call fsync($h) firstLaravel's Storage facade (Flysystem) adds the abstraction that Go gets from fs.FS for reading; Go's standard library has no write-side abstraction, so large Go projects define a small interface (Put, Get, Delete) and implement it for disk and for S3. PHP-FPM workers die after a request and take their file handles with them; a Go process lives for weeks, so a leaked descriptor accumulates until too many open files.
Lab
Everything runs on a laptop with Go 1.24 or later; no Docker. Outputs marked "(real)" were produced on the host while writing this page (Go 1.27.4, macOS arm64, umask 022); anything else is labelled "expected, not run" (EN) and its Persian counterpart «خروجی موردانتظار؛ اجرا نشده».
cd docs/snippets/go/files-directories-embed/go
gofmt -l . # no output
go vet ./... # no output
go test -race ./... # ok for 10 packages with tests (real); xdev and leak have no tests1. Error texts from the file API (real)
A ten-line program creates a file f, a directory d and a read-only file ro and prints each error:
open missing.txt: no such file or directory
rename f d: file exists
read d: is a directory
remove d: directory not empty
open f: file exists
open ro: permission denied
openat ../f: path escapes from parent
write closed: file already closed
write f: bad file descriptor2. embed build errors (real)
go build ./...
# pattern ../secret.txt: invalid pattern syntax
# pattern nothing*.txt: no matching files found
# pattern link.txt: cannot embed irregular file link.txt
# ./main.go:4:3: misplaced go:embed directive
# ./main.go:4:5: invalid go:embed: multiple files for type string3. The traversal tests (real)
go test -race -v ./rootdemo
# --- PASS: TestNaiveLeaks
# --- PASS: TestLexicalStopsDotDotButNotSymlink
# --- PASS: TestRootStopsBoth
# --- PASS: TestRootAllowsInnerDotDotThe first test proves the leak, the second that IsLocal misses the symlink, the third that os.Root refuses both with path escapes from parent.
4. Token too long (real)
go test -race -v -run 'TestTokenTooLong|TestBufferRaisesLimit|TestReaderHasNoLimit' ./scan
# --- PASS: TestTokenTooLong
# --- PASS: TestBufferRaisesLimit
# --- PASS: TestReaderHasNoLimit5. Atomic replace under a concurrent reader (real)
go test -race -v -run 'TestReadersNeverSeePartial' ./atomicwrite
# --- PASS: TestReadersNeverSeePartialLab 8 shows the same test failing when the helper is replaced by os.WriteFile.
6. Rename between two paths (real on one file system, expected, not run across devices)
go run ./xdev /tmp/a /tmp/b
# renamed (real, same file system)
go run ./xdev /tmp/a /var/tmp/b # Linux with /tmp on tmpfs
# rename /tmp/a /var/tmp/b: invalid cross-device link (expected, not run)7. Descriptor leak (real, host limit)
go run ./leak
# failed after 92156 files: open /dev/null: too many open filesThe host allows about 92 000 descriptors, so the loop ran that long before failing. With ulimit -n 64 first, the same program stops after about sixty files (expected, not run: the limit could not be lowered inside the sandbox that produced the real run). The cause is defer f.Close() inside the loop: every file stays open until main returns.
8. The non-atomic variant fails the reader test (real)
Replace the body of atomicwrite.WriteFile with return os.WriteFile(path, data, perm) and run the same test:
go test -count=1 -run TestReadersNeverSeePartial ./atomicwrite
# --- FAIL: TestReadersNeverSeePartial (0.00s)
# atomicwrite_test.go:84: partial file of 0 bytesCommon misconceptions
| Belief | Reality |
|---|---|
os.Create creates a new file | It creates or truncates; use O_EXCL to refuse existing files |
os.WriteFile is atomic | It truncates and writes in several calls and can leave a partial file |
Write returned, so the data is on disk | It is in the page cache until Sync (and even then the drive may cache) |
defer f.Close() is enough for written files | Close can return the real write error; capture it |
filepath.Join makes paths safe | It cleans lexically; ../ and symlinks still escape |
filepath.IsLocal stops symlink attacks | It is lexical only; use os.Root |
os.DirFS confines access to the directory | A symlink inside can point out; Root.FS confines |
os.Rename always replaces atomically | Only inside one file system, and not on Windows |
bufio.Scanner handles any line | 64 KiB per token by default; check sc.Err() |
bufio.Writer writes immediately | Nothing is sent until the buffer fills or Flush |
//go:embed can reach parent directories or symlinks | No .., no symlinks, and dotfiles are skipped unless all: |
| Embedded files change when the disk file changes | They are frozen at build time |
| Temp files are deleted for me | Only t.TempDir() cleans up |
WalkDir follows symlinks | It does not; a link is one entry |
| A lock file stops other processes | It is a convention, and crashes leave it behind |
Cheat sheet
| Topic | What to remember |
|---|---|
| open | Open read, Create truncates, OpenFile flags and perm; perm only on create |
O_EXCL | with O_CREATE, fails if the name exists; atomic check-and-create |
| close | Close can fail on writes; keep its error |
| whole file | os.ReadFile/WriteFile; fine when small, not atomic |
Stat | follows symlinks; Lstat does not; test with errors.Is(err, fs.ErrNotExist) |
MkdirAll / RemoveAll | idempotent; never feed RemoveAll unchecked input |
Rename | atomic in one file system on Unix; keep the temp file in the target directory |
| atomic write | temp file, Sync, Rename, directory Sync |
ReadDir / WalkDir | one level sorted / whole tree lexical, no symlink following |
path vs filepath | URLs and fs.FS names vs OS paths |
| traversal | IsLocal/Localize for the name, os.Root for the access |
fs.FS | slash names, no ..; fs.Sub, fs.ReadFile, fstest.MapFS |
embed | package-relative, no .., no symlinks, all: for dotfiles; fs.Sub + http.FS |
| temp | CreateTemp 0600, MkdirTemp 0700, t.TempDir() auto-clean |
bufio.Scanner | 64 KiB limit, Buffer(buf, max), check Err() |
bufio.Writer | Flush and check its error |
| large files | io.Copy, SectionReader, streaming decoders |
| watching | fsnotify on the parent directory, debounce; or poll |
| umask | requested bits &^ umask; Chmod is exact |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What is the difference between os.Open, os.Create and os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)? Must-know
Answer
Answer: Open is read-only and fails if the file is absent. Create creates or truncates and opens read-write. The OpenFile form creates the file only if it does not exist and fails with fs.ErrExist otherwise; the permission applies only when it creates.
2 — Why can ignoring the error from f.Close() lose data? Important
Answer
Answer: A write returns when the kernel accepted the bytes. Delayed errors (quota, full disk, network file system) can surface at Close, so a writer must return that error.
3 — List the steps of a crash-safe file replace and say what each protects against. Important
Answer
Answer: Create a temp file in the same directory (rename stays atomic), write and set the mode, Sync the temp file (data on disk before the name flips), Close, Rename over the target (readers see old or new), Sync the directory (the rename itself survives a crash).
4 — A function does os.ReadFile(filepath.Join("/srv/public", name)) with a name from a URL. Give two attacks and the fix. Must-know
Answer
Answer: ../secret and a symlink inside /srv/public that points outside. Validate with filepath.IsLocal and open through os.OpenRoot("/srv/public") (or os.OpenInRoot), which rejects both with path escapes from parent.
5 — What does bufio.Scanner: token too long mean and how do you handle it? Must-know
Answer
Answer: A line exceeded MaxScanTokenSize (64 KiB). Scan returned false and Err() returned bufio.ErrTooLong. Raise the limit with Scanner.Buffer(buf, max) or read with Reader.ReadString and your own cap, and always check sc.Err().
6 — Why can a bufio.Writer lose the last lines of output? Must-know
Answer
Answer: Writes sit in a 4 KiB buffer until it fills or Flush is called; exiting without Flush drops the tail. Flush also returns the first write error.
7 — Which of these does go:embed accept: ../shared/x.txt, a symlink, static, all:static? Good to know
Answer
Answer: static (a directory, minus names starting with . or _) and all:static (including them). .. gives invalid pattern syntax, a symlink gives cannot embed irregular file.
8 — How do you serve an embedded static/ directory at the site root? Important
Answer
Answer: sub, _ := fs.Sub(embeddedFS, "static") then http.FileServer(http.FS(sub)); fs.Sub removes the static/ prefix.
9 — What does fs.ValidPath("a/../b") return, and why does it matter? Important
Answer
Answer: false. io/fs names must be slash-separated, unrooted and contain no . or .. elements, which makes an fs.FS safe by construction against lexical traversal.
10 — Why must a temp file used for an atomic write be created in the target's directory? Important
Answer
Answer: Rename is atomic only within one file system; /tmp is often a different one (tmpfs), giving invalid cross-device link.
11 — What is the difference between O_EXCL lock files and flock? Good to know
Answer
Answer: A lock file stays after a crash and must be cleaned up by policy. flock is held on an open file and is dropped by the kernel when the process dies, but it is Unix-only and advisory.
12 — Why watch the parent directory with fsnotify instead of the file? Good to know
Answer
Answer: Editors and deploy tools replace files by rename, which removes the watched inode; a directory watch sees the new file arrive and you filter by name.
Glossary
| Term | Meaning |
|---|---|
os.File | handle around an operating-system file descriptor |
| file descriptor | small integer the kernel uses to track an open file |
os.Open | open read-only |
os.Create | create or truncate and open read-write |
os.OpenFile | open with chosen flags and permission bits |
O_EXCL | with O_CREATE, fail if the name already exists |
O_APPEND | every write goes to the current end of the file |
O_TRUNC | empty the file on open |
FileMode | type bits and permission bits of a file (fs.FileMode) |
| umask | process-wide mask removed from requested permission bits at creation |
FileInfo | metadata returned by Stat: name, size, mode, mod time |
DirEntry | a directory listing entry with name and type, no stat needed |
os.ReadFile / os.WriteFile | whole-file helpers; the write is not atomic |
PathError | error type with Op, Path and Err for file operations |
| atomic rename | name switch seen entirely or not at all by other processes |
fsync | flush file data (or a directory) to stable storage |
| durability | the property that acknowledged data survives a crash |
| page cache | kernel memory holding recently read and written file data |
| symlink | file whose content is a path to another file |
filepath.WalkDir | recursive walk in lexical order, not following symlinks |
SkipDir | return value that prunes a directory during a walk |
path | slash-only path functions for URLs and fs.FS names |
path/filepath | OS-specific path functions for files on disk |
filepath.Clean | lexical simplification of a path |
filepath.Join | join elements and clean the result |
filepath.Abs | absolute form using the working directory |
filepath.Rel | relative path from a base to a target |
filepath.Glob | files matching a shell-style pattern in one directory level |
| path traversal | getting a program to open a file outside the intended directory |
filepath.IsLocal | lexical test that a name stays inside the directory it is joined to |
filepath.Localize | converts a slash path from untrusted input into a safe OS path |
os.Root | directory handle whose operations cannot escape the directory (Go 1.24) |
| TOCTOU | time-of-check to time-of-use race between a check and the operation |
io/fs | read-only file system interfaces and helpers (Go 1.16) |
fs.FS | interface with Open(name); names are slash-separated and unrooted |
fs.ValidPath | validates an fs.FS name |
fs.Sub | fs.FS view of a subdirectory |
fstest.MapFS | in-memory fs.FS for tests |
fstest.TestFS | checks that an fs.FS implementation follows the contract |
go:embed | directive that embeds files into the binary at build time |
embed.FS | read-only file tree embedded in the binary |
http.FS | adapter from fs.FS to http.FileSystem |
os.CreateTemp | create a unique private temp file (mode 0600) |
os.MkdirTemp | create a unique private temp directory (mode 0700) |
t.TempDir | per-test directory removed automatically |
bufio.Reader | buffered reader with ReadString, ReadBytes, Peek |
bufio.Writer | buffered writer that needs Flush |
bufio.Scanner | token reader with a size limit |
| token too long | bufio.ErrTooLong, a token over the Scanner limit (64 KiB default) |
Scanner.Buffer | sets the initial buffer and the maximum token size |
ReadString | read up to and including a delimiter, no length limit |
io.Copy | stream a reader into a writer with a reusable buffer |
io.SectionReader | window over an io.ReaderAt |
O_EXCL lock | lock file created exclusively; a convention, not enforced |
flock | advisory file lock released by the kernel when the process dies |
fsnotify | third-party package for file system change events |
| ReadLinkFS | io/fs interface for reading symbolic links (Go 1.25) |
References
All URLs returned HTTP 200 when fetched on 26 November 2026; pages and go doc output saved under the scratchpad sources/files-directories-embed/ folder.
- Go 1.24 release notes, "Directory-limited filesystem access": go.dev/doc/go1.24
- Go blog, "Traversal-resistant file APIs" (Damien Neil, 12 March 2025): go.dev/blog/osroot
- Go 1.25 release notes (
ReadLinkFS, moreRootmethods): go.dev/doc/go1.25 - Go 1.23 release notes (
filepath.Localize,os.CopyFS): go.dev/doc/go1.23 - Go 1.21 release notes: go.dev/doc/go1.21
- Go 1.20 release notes (
filepath.IsLocal): go.dev/doc/go1.20 - Go 1.16 release notes (
io/fs,embed,ioutilmoves): go.dev/doc/go1.16 - Source of
os(Root,File, temp files): go.dev/src/os/root.go, go.dev/src/os/file.go, go.dev/src/os/tempfile.go, go.dev/src/os/dir.go - Source of
embed: go.dev/src/embed/embed.go - Source of
io/fs: go.dev/src/io/fs/fs.go, go.dev/src/io/fs/walk.go, go.dev/src/io/fs/sub.go - Source of
bufio: go.dev/src/bufio/scan.go, go.dev/src/bufio/bufio.go - Source of
path/filepath: go.dev/src/path/filepath/path.go, go.dev/src/path/filepath/match.go - Effective Go: go.dev/doc/effective_go
- The Go Programming Language Specification: go.dev/ref/spec
- Go Code Review Comments: go.dev/wiki/CodeReviewComments
- fsnotify: github.com/fsnotify/fsnotify and its README
- PHP manual,
fopen: php.net/manual/en/function.fopen.php - PHP manual,
file_get_contents: php.net/manual/en/function.file-get-contents.php - PHP manual,
SplFileObject: php.net/manual/en/class.splfileobject.php