Skip to content

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 forGo to
Tables you can memorise in one minuteEverything in one minute
Why files need so much careWhy it exists
Which Go release added embed, io/fs, os.RootWhere it comes from
os.Open against os.Create against os.OpenFileOpening files
0o644, FileMode, umaskPermissions and umask
Read, Write, Seek, Close returning an errorReading, writing, seeking, closing
os.ReadFile, os.WriteFile, os.Stat, FileInfoWhole-file helpers and Stat
MkdirAll, Remove, RemoveAll, Rename, ReadDirDirectories
filepath.WalkDir, SkipDir, symlinksWalking a tree
path against path/filepath, Join, Clean, Rel, Globpath and path/filepath
../../etc/passwd, filepath.IsLocal, os.RootPath traversal
fs.FS, fs.Sub, fstest.MapFSio/fs
//go:embed, embed.FS, http.FSembed
os.CreateTemp, os.MkdirTemp, t.TempDir()Temp files and directories
bufio.Scanner, token too long, ReadString, Flushbufio
Crash-safe replace, fsync, durabilityAtomic writes and fsync
Lock files, O_EXCL, flockLocking and O_EXCL
Multi-gigabyte files, io.Copy, io.SectionReaderLarge files
fsnotify, config reloadWatching files
Windows separators, reserved names, no atomic renameWindows differences
Error texts and version gatesMechanics
Upload store, config reload, log rotation in codeSolving the classic problems
Which API for which jobChoosing
One process to many servicesIn architecture
file_get_contents, fopen, SplFileObjectFor PHP/Laravel developers
Run it yourselfLab

Everything in one minute ​

APIPlain wordsTiny exampleGotcha
os.OpenOpen a file read-onlyf, err := os.Open("a.txt")Fails if it does not exist; you must Close
os.CreateCreate or truncate, then read-writef, err := os.Create("a.txt")Silently empties an existing file
os.OpenFileChoose flags and permissions yourselfos.OpenFile(p, os.O_WRONLY, 0o644)The permission argument only matters when the file is created
os.ReadFileWhole file into memoryb, err := os.ReadFile(p)A 5 GiB file becomes 5 GiB of heap
os.WriteFileCreate or truncate, write, closeos.WriteFile(p, b, 0o644)Not atomic; a crash can leave a partial file
os.StatMetadata without openingfi, err := os.Stat(p)Follows symlinks; Lstat does not
os.MkdirAllmkdir -pos.MkdirAll(dir, 0o755)Returns nil when it already exists
os.RemoveAllrm -rfos.RemoveAll(dir)Returns nil when the path is missing; typos delete trees
os.RenameMove or replaceos.Rename(tmp, final)Atomic only on one file system, not on Windows
os.ReadDirOne directory level, sortedents, err := os.ReadDir(d)Not recursive
filepath.WalkDirWhole tree, lexical orderfilepath.WalkDir(root, fn)Does not follow symlinks
filepath.JoinJoin and cleanfilepath.Join(base, name)Does not stop ../ escapes
filepath.IsLocalIs this name safe to join?filepath.IsLocal(name)Lexical only; a symlink inside can still escape
os.OpenRootDirectory-limited file accessr, _ := os.OpenRoot(dir)Does not limit mount points
fs.FSRead-only tree interfacefs.ReadFile(fsys, "a/b")Slash paths, no .., no leading /
//go:embedPut files into the binary//go:embed staticNo .., no symlinks, dotfiles skipped
os.CreateTempPrivate unique fileos.CreateTemp("", "x-*.json")You must remove it
bufio.ScannerRead lines or tokenssc.Scan()Stops at 64 KiB per token, check sc.Err()
bufio.WriterBatch small writesbw.Flush()Data is lost without Flush
f.Syncfsync: push to diskf.Sync()Needed before the rename for durability
Go versionWhat changed for filesWhere
1.16io/fs, embed, os.ReadFile, os.WriteFile, os.ReadDir, os.CreateTemp, os.MkdirTemp, os.DirFS; io/ioutil deprecatedio/fs, embed
1.15testing.T.TempDirTemp files
1.20filepath.IsLocalPath traversal
1.21slices, maps, min/max help with directory resultsWalking a tree
1.23filepath.Localize, os.CopyFSPath traversal
1.24os.Root, os.OpenRoot, os.OpenInRoot, Root.FSPath traversal
1.25io/fs.ReadLinkFS; Root.ReadFile, WriteFile, MkdirAll, RemoveAll, Rename and morePath traversal, io/fs
MistakeSymptomSection
Ignoring the error from Close after writingSilent data loss on a full disk or NFSReading, writing, seeking, closing
os.WriteFile over a live configReader sees an empty or half fileAtomic writes and fsync
Rename without fsync firstNew name, zero bytes after power lossAtomic writes and fsync
filepath.Join(base, userInput)Reads /etc/passwdPath traversal
bufio.Scanner on a long linebufio.Scanner: token too long, loop ends earlybufio
Forgetting bufio.Writer.FlushLast lines never writtenbufio
defer f.Close() in a loop over many filesToo many open filesReading, writing, seeking, closing
//go:embed ../xinvalid pattern syntaxembed
Rename across file systemsinvalid cross-device linkAtomic writes and fsync
Lock file left by a crashed processService refuses to startLocking 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 assumptionWhat the system really doesConsequence
Write returned, so the data is savedIt is in the page cache; the disk may be seconds behindA power cut loses it unless you Sync
Close cannot failClose can report a deferred write errorA full disk or a lost NFS mount shows up only there
A path names one fileA path is resolved at use time through symlinks and ..Check-then-open races (TOCTOU)
Rename replaces a file safelyAtomic name switch, but only inside one file systemCross-device rename fails; Windows is not atomic
A line is a short stringLines can be any lengthScanner stops at 64 KiB by default
Files are on a diskFiles can be on NFS, overlayfs, tmpfs, a ConfigMap mountLatency, 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 ​

  1. "os.WriteFile is 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.
  2. "filepath.Join sanitises paths." It only cleans them; Join("/srv/public", "../secret") is /srv/secret. Validate with filepath.IsLocal, or better, open through os.Root.
  3. "bufio.Scanner reads any text file." It reads tokens up to 64 KiB, and when a token is longer it stops and reports the problem only through sc.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".

ChangeReleasePrimary source
io/fs, fs.FS, os.DirFS, os.ReadDir, os.ReadFileGo 1.16go.dev/doc/go1.16
//go:embed and package embedGo 1.16go.dev/doc/go1.16
filepath.IsLocal ("lexically local to a directory")Go 1.20go.dev/doc/go1.20
filepath.Localize, os.CopyFSGo 1.23go.dev/doc/go1.23
os.Root, os.OpenRoot, os.OpenInRootGo 1.24go.dev/doc/go1.24, go.dev/blog/osroot
fs.ReadLinkFS, more Root methodsGo 1.25go.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 end

Real 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.

FlagMeaningTypical useGotcha
O_RDONLYread onlyos.Openwriting fails with bad file descriptor
O_WRONLYwrite onlylogs, outputreading fails
O_RDWRread and writeos.Create, databasesone shared offset for both
O_CREATEcreate when missingmost writersneeds a permission argument
O_EXCLwith O_CREATE: fail if presentlocks, unique fileson a network file system, check that your mount honours it
O_TRUNCempty a regular file on openrewritingdata loss before you write anything
O_APPENDwrites go to the endlogsWriteAt returns an error on such a file
O_SYNCeach write waits for the diskrare, slowusually Sync() at checkpoints instead

Fix / how to use it: create-if-absent with an exclusive flag and a deferred Close that keeps its error:

go
// 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.

OctalSymbolicUsed for
0o600-rw-------secrets, keys, temp files from CreateTemp
0o644-rw-r--r--ordinary files
0o640-rw-r-----files shared with a group
0o700drwx------private directories, MkdirTemp
0o755drwxr-xr-xpublic directories, binaries
0o666 / 0o777before umaskwhat 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 closed

Real 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).

OperationReturnsError you will see
Read at the end0, io.EOFEOF is a normal end, not a failure
Write on a read-only file0, errwrite f: bad file descriptor
Write after Close0, errwrite f: file already closed
ReadAt past the endshort count, io.EOFEOF
Seek before the start0, errseek f: invalid argument
Close twiceerrclose f: file already closed

Fix / how to use it: the pattern from CreateNew above keeps the first error:

go
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.

NeedUseNote
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 streamfi.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.

CallMissing parentAlready existsNon-empty directory
os.Mkdirerror no such file or directoryerror file existsnot applicable
os.MkdirAllcreates parentsnil if a directory; error if a filenot applicable
os.Removeerror no such file or directoryremoves iterror directory not empty
os.RemoveAllnilremoves treeremoves tree
os.Renameerrorreplaces 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 continue

Real 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.

NeedUseCost
One folder, sortedos.ReadDirone directory read
One folder, unsorted, streaming(*os.File).ReadDir(n)batches of n entries
Whole tree, no statfilepath.WalkDirone directory read per folder
Whole tree with sizesWalkDir and d.Info()an extra lstat per entry
Whole tree on an fs.FSfs.WalkDirslash paths, works on embed.FS
Match a patternfilepath.Glob, fs.Globnot 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:

go
// 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.

Functionpathpath/filepathNote
Separatoralways /os.PathSeparatorfilepath.ToSlash and FromSlash convert
Join, Clean, Base, Dir, Ext, Split, Matchyesyessame lexical rules
Abs, Rel, EvalSymlinks, Glob, WalkDirnoyesneed the OS
IsAbs, IsLocal, Localize, VolumeNameIsAbs onlyyesWindows aware
Typical useURLs, io/fs, archive namesfiles on diskpick 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:

go
// 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 later

Real 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.

DefenceStops ../xStops absolute namesStops symlink escapeStops TOCTOUGo version
strings.HasPrefix(Clean(p), base)partly, easy to get wrongnononoany
filepath.IsLocal(name)yesyesnono1.20
filepath.Localize(name)yesyesnono1.23
fs.ValidPath(name)yesyesno (depends on the FS)no1.16
os.DirFS(dir) alonevalidates namesvalidates namesno ("DirFS is therefore not a general substitute for a chroot-style security mechanism")no1.16
os.Root / os.OpenInRootyesyesyesyes1.24
Root.FS()yesyesyesyes1.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.

go
// 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
}
filepath.Join(base, name)base = /srv/publicname = ../secret.txtClean gives /srv/secret.txt (outside)IsLocal(name) stops this lexical case/srv/public/link -> ../secret.txtis a clean, local name that still escapescheck then open = TOCTOU race windowos.OpenRoot(base).Open(name)root holds a directory descriptoreach component opened relative to ita/../b allowed (stays inside)../secret.txt -> path escapes from parentsymlink leaving the root -> same errorno separate check, so no race windowmount points are not limited

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 consistent

Real 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.

ProviderPackageWritable?Notes
os.DirFS(dir)osnosymlinks can leave dir; use Root.FS to confine
(*os.Root).FS()osnoconfined, Go 1.24
embed.FSembednocompile-time snapshot
fstest.MapFStesting/fstestbuild it in codeData, Mode, ModTime per entry
zip.Readerarchive/zipnoimplements fs.FS
fs.Sub(fsys, dir)io/fsnocheap view
os.CopyFS(dir, fsys)oswrites to diskGo 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:

go
// 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)
}
Providersos.DirFS("/srv/data")embed.FS (compile time)fstest.MapFS (tests)zip.Reader, fs.Sub(...)fs.FSOpen(name) (fs.File, error)slash paths, no .. no /fs.ValidPath(name)Consumersfs.ReadFile, fs.WalkDirhttp.FS + http.FileServertemplate.ParseFSfs.Glob, your own codeWrite consumers against fs.FS and the same code runs on disk, in the binary and in a unit test.

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 rebuilt

Real 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 typePatterns allowedResultTypical use
stringexactly one filecontents as textversion file, one template
[]byteexactly one filecontents as bytesicon, certificate
embed.FSmany files and directoriesread-only treestatic 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 foundevery pattern needs a match
pattern link.txt: cannot embed irregular file link.txtsymlinks are rejected
misplaced go:embed directivedirective not directly above a variable
invalid go:embed: multiple files for type stringtwo 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:

go
// 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 ends

Real 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.

NeedUseCleanup
Scratch file in productionos.CreateTemp(dir, "x-*")defer os.Remove(f.Name())
Scratch directoryos.MkdirTemp(dir, "x-")defer os.RemoveAll(path)
File in a testfilepath.Join(t.TempDir(), "x")automatic
Staging file for a renameos.CreateTemp(filepath.Dir(target), ...)rename or remove on error
Default directoryos.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:

go
// 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; NewReaderSize for others) offers ReadString(delim) and ReadBytes(delim) (return the data including the delimiter, together with io.EOF for a last line without one), ReadLine (low level, returns isPrefix for long lines; the documentation steers you to ReadString or a Scanner), ReadRune, Peek, Discard. There is no maximum line length; memory grows with the line.
  • bufio.NewScanner(r) reads tokens with a SplitFunc: ScanLines (default; strips \n and a preceding \r), ScanWords, ScanRunes, ScanBytes, or your own. The default maximum token is bufio.MaxScanTokenSize, 64 KiB; Scanner.Buffer(buf, max) raises it (call it before the first Scan). When a token is too long, Scan stops and Err() returns bufio.ErrTooLong. A split function that returns empty tokens without progress panics with bufio.Scan: too many empty tokens without progressing.
  • bufio.NewWriter(w) (default 4096 bytes; NewWriterSize) collects writes; Flush sends the rest. After the first write error the Writer is sticky: every later write and Flush return that error, so one check at Flush is 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 disk

Real 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.

TaskUseLimit or cost
Lines up to a known maximumScanner with Buffer(make([]byte, 0, 64*1024), 1<<20)fails with ErrTooLong above the maximum
Lines of unknown lengthReader.ReadString('\n')memory grows with the line; add your own cap
Binary framingio.ReadFull and encoding/binarysee io package
Many small writesbufio.Writer, one Flush at the endforgetting Flush loses data
Word or rune tokensScanner with ScanWords or ScanRunessame 64 KiB token cap
Custom delimiterScanner.Split(func)return (0, nil, nil) to ask for more data
Peek without consumingReader.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:

go
// 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()
}
Readingfile (syscalls)bufio buffer 4 KiB defaultone read(2) fills many linesScanner.Scan()max token 64 KiBReader.ReadStringno limit, memory growsWritingWriteString x 1000small writesbufio.Writer buffersent when full or on Flush()file (syscall)Forget Flush and the tail of your output is lost; forget sc.Err() and "token too long" looks like a normal end of file.Buffered data is in your process; it is not yet on disk even after Flush (see fsync).

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 durable

Real 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.

MethodAtomic for readersSurvives power lossCost
os.WriteFile in placeno (truncates first)noone syscall sequence
Temp file and Rename, no Syncyesno (may be empty after a crash)cheap
Temp file, Sync, Renameyesdata yes, rename maybeone fsync
Temp file, Sync, Rename, directory Syncyesyes (on a file system that honours fsync)two fsyncs, milliseconds each
Append-only log plus checkpointyesyesdesign cost; this is what databases do
O_SYNC/O_DSYNC on every writeper writeper writeslowest

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:

go
// 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()
}
1 CreateTempconfig.json.tmp-123same directory2 Write + Chmodbytes sit in thepage cache3 f.Sync() fsyncdata reaches thedisk, then Close4 os.Renametmp becomesconfig.json5 fsync(directory)the rename is durableCrash pointsbefore step 4: old config.json intact, stray tmp fileafter step 4 before step 5: old or new, never a mixSkip the fsync in step 3 and a power cut can leave the new name pointing at an empty file.Rename is atomic only inside one file system, which is why the temp file lives next to the target.

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 succeeds

Real 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.

TechniqueCleans up after a crashCross-platformWorks across hosts
O_EXCL lock fileno (stale file)yesonly where the shared file system honours O_EXCL
flock on a held fileyesUnix onlyNFS-dependent
LockFileExyesWindows onlyno
Database advisory lock or row lockyes (connection closes)yesyes, see Locks & Concurrency Control
Lease in etcd, Redis or a databaseyes (TTL)yesyes

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 heap

Real 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.

PatternMemorySeekableUse
os.ReadFilewhole filen/asmall config and fixtures
io.Copy32 KiBnocopy and upload
io.SectionReaderwindow onlyyesrange requests, chunks
bufio.Reader.ReadLinebuffer sizenovery long lines
Seek(-n, io.SeekEnd)n bytesyestail of a file
mmappage cacheyesdatabases, 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:

go
// 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 error

Real 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.

MechanismLatencyPlatform supportFailure mode
fsnotifymillisecondsLinux, BSD, macOS, Windowslost watches, limits, network file systems
Poll Stat every N secondsN secondseverywheremisses nothing, costs a syscall per tick
SIGHUP to reloadimmediateUnixneeds an operator or a supervisor
Content hash compare on a timerN secondseverywherecost 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.

TopicLinux and macOSWindows
Separator/\ (/ also accepted)
Rename over an existing fileatomicnot atomic; fails if the target is open
Delete an open fileallowed (inode lives until closed)usually refused
Casesensitive on Linux; insensitive by default on macOSinsensitive
Reserved namesnoneNUL, CON, PRN, AUX, COM1 ...
Permission bitsfullread-only flag only
Directory fsyncworksnot meaningful
Symlinksnormalprivilege 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 withCause
open missing.txt: no such file or directoryerrors.Is(err, fs.ErrNotExist)path absent or a parent missing
open f: file existserrors.Is(err, fs.ErrExist)O_EXCL on an existing name
open ro: permission deniederrors.Is(err, fs.ErrPermission)mode or ownership forbids it
read d: is a directoryerrors.Is(err, syscall.EISDIR)reading a directory as a file
remove d: directory not emptyerrors.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 closederrors.Is(err, os.ErrClosed)use after Close
write f: bad file descriptorerrors.Is(err, syscall.EBADF)writing a read-only file
openat ../f: path escapes from parentmatch os.ErrInvalid-style textos.Root refused the name
bufio.Scanner: token too longerrors.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/ago:embed with ..
pattern nothing*.txt: no matching files found (build)n/ago:embed matched nothing

Version gates, in one table Must-know ​

FeatureNeedsIf your go.mod is older
os.ReadFile, os.WriteFile, os.CreateTemp, os.MkdirTemp, os.ReadDir, io/fs, embedGo 1.16use io/ioutil equivalents; no embed
t.TempDirGo 1.15use os.MkdirTemp and t.Cleanup
filepath.IsLocal, filepath.SkipAllGo 1.20write the checks by hand
filepath.Localize, os.CopyFSGo 1.23use IsLocal after FromSlash
os.Root, os.OpenRoot, os.OpenInRoot, Root.FSGo 1.24use IsLocal and accept the symlink gap
fs.ReadLinkFS, Root.ReadFile/WriteFile/MkdirAll/RemoveAll/RenameGo 1.25use Root.Open and copy

From a call to the kernel ​

Go callTypical system call (Linux)Notes
os.Open, os.OpenFileopenatreturns a file descriptor; O_CLOEXEC is added so children do not inherit it
f.Read, f.Writeread, writeone call per Read; hence bufio
f.ReadAt, f.WriteAtpread, pwritedo not move the shared offset
f.Seeklseek
f.SyncfsyncmacOS: fcntl(F_FULLFSYNC)
f.Closeclosecan return a delayed error
os.Stat, os.Lstatfstatatfollows or does not follow a link
os.ReadDirgetdents64reads in batches, sorts in user space
os.Renamerenameatatomic in one file system
os.Removeunlinkattries file then directory
os.Root methodsthe openat family, relative to the root's directory descriptorper 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 ​

ToolWhat it catches
go vetprintf 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 -raceraces 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/fdleaked descriptors (expected, not run)
strace -f -e trace=file,fsyncexactly which syscalls your code makes (expected, not run)
fstest.TestFSan fs.FS that breaks the contract

Solving the classic problems ​

ProblemSolutionWhy it worksCost or limit
Config rewritten while readtemp file, Sync, Renamereaders see old or newsame directory, needs write access to it
Untrusted file nameIsLocal then os.Rootlexical check plus kernel confinementGo 1.24, mount points not limited
Lines longer than 64 KiBScanner.Buffer with a cap, or ReadStringexplicit limit or nonememory grows with the line
Output missing its taildefer bw.Flush() and check its errorbuffer emptiedforgetting it is silent
Two instances of a jobO_EXCL lock file or flockkernel check-and-createstale files, host-local
Tests need filest.TempDir() or fstest.MapFScleanup and no diskMapFS is not a real disk
Ship templates and assets//go:embed, fs.Sub, http.FSsingle binaryrebuild to change
Huge file in constant memoryio.Copy, SectionReader, streaming decodersone bufferno random access in io.Copy
Directory walk skipping junkWalkDir and SkipDirprunes subtrees cheaplydoes not follow symlinks
Cleanup of old filesWalkDir, check d.Info().ModTime(), Removeone passrace 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.

sql
-- 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 ​

SituationUseExtra techniqueReason
Read a small config at start-upos.ReadFilefs.ReadFile if the source may be embeddedsimple, bounded
Replace a config or state fileatomic write helperdirectory Sync if durability mattersno partial file
Read a big text filebufio.Scanner with Bufferhandle sc.Err()line-at-a-time, bounded memory
Lines of unknown sizebufio.Reader.ReadStringcap the totalno token limit
Write many small recordsbufio.Writerdefer Flush and check the errorfewer syscalls
Serve static assetsembed.FS, fs.Sub, http.FSos.DirFS in developmentone binary
Name comes from a userIsLocal then os.Roota store keyed by hash, not by nametraversal and symlink safety
Read-only logic under testaccept fs.FSfstest.MapFSno disk, fast
Scratch dataos.CreateTemp / MkdirTempdefer removalprivate and unique
One job at a time on a hostflock or O_EXCL lockpid in the filecheap
One job at a time in a clusterdatabase or lease lockfencing tokenfiles do not span hosts
React to file changesfsnotify on the directorydebounce and validatelow latency
Copy a big fileio.Copycopy_file_range path via *os.Fileconstant memory
Share files between servicesobject storage, not a shared diskpresigned URLssee 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× ​

ScaleFile concernAction
1x (one process)correctness: Close, Flush, partial writes, traversalatomic writes, os.Root, tests with t.TempDir()
10x (one busy host)descriptors, page cache, fsync latency, directory with millions of entriesraise 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 objectsobject storage, content-addressed keys, presigned uploads, a CDN, metadata in the database
anyuntrusted names, hostile archivesos.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.

PHPGoDifference
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 WriteGo 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 iterationbufio.Scanner or Reader.ReadStringPHP 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.CreateTempGo creates with 0600 and exclusive create
realpath()filepath.EvalSymlinks plus Abs
glob()filepath.Globno ** in either, Go has no GLOB_BRACE
Storage::disk('local')->put()your own wrapper over fs.FS and os.Rootno abstraction layer is built in
php
// 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) first

Laravel'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 «خروجی موردانتظار؛ اجرا نشده».

bash
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 tests

1. 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 descriptor

2. embed build errors (real) ​

bash
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 string

3. The traversal tests (real) ​

bash
go test -race -v ./rootdemo
# --- PASS: TestNaiveLeaks
# --- PASS: TestLexicalStopsDotDotButNotSymlink
# --- PASS: TestRootStopsBoth
# --- PASS: TestRootAllowsInnerDotDot

The 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) ​

bash
go test -race -v -run 'TestTokenTooLong|TestBufferRaisesLimit|TestReaderHasNoLimit' ./scan
# --- PASS: TestTokenTooLong
# --- PASS: TestBufferRaisesLimit
# --- PASS: TestReaderHasNoLimit

5. Atomic replace under a concurrent reader (real) ​

bash
go test -race -v -run 'TestReadersNeverSeePartial' ./atomicwrite
# --- PASS: TestReadersNeverSeePartial

Lab 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) ​

bash
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) ​

bash
go run ./leak
# failed after 92156 files: open /dev/null: too many open files

The 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:

bash
go test -count=1 -run TestReadersNeverSeePartial ./atomicwrite
# --- FAIL: TestReadersNeverSeePartial (0.00s)
#     atomicwrite_test.go:84: partial file of 0 bytes

Common misconceptions ​

BeliefReality
os.Create creates a new fileIt creates or truncates; use O_EXCL to refuse existing files
os.WriteFile is atomicIt truncates and writes in several calls and can leave a partial file
Write returned, so the data is on diskIt is in the page cache until Sync (and even then the drive may cache)
defer f.Close() is enough for written filesClose can return the real write error; capture it
filepath.Join makes paths safeIt cleans lexically; ../ and symlinks still escape
filepath.IsLocal stops symlink attacksIt is lexical only; use os.Root
os.DirFS confines access to the directoryA symlink inside can point out; Root.FS confines
os.Rename always replaces atomicallyOnly inside one file system, and not on Windows
bufio.Scanner handles any line64 KiB per token by default; check sc.Err()
bufio.Writer writes immediatelyNothing is sent until the buffer fills or Flush
//go:embed can reach parent directories or symlinksNo .., no symlinks, and dotfiles are skipped unless all:
Embedded files change when the disk file changesThey are frozen at build time
Temp files are deleted for meOnly t.TempDir() cleans up
WalkDir follows symlinksIt does not; a link is one entry
A lock file stops other processesIt is a convention, and crashes leave it behind

Cheat sheet ​

TopicWhat to remember
openOpen read, Create truncates, OpenFile flags and perm; perm only on create
O_EXCLwith O_CREATE, fails if the name exists; atomic check-and-create
closeClose can fail on writes; keep its error
whole fileos.ReadFile/WriteFile; fine when small, not atomic
Statfollows symlinks; Lstat does not; test with errors.Is(err, fs.ErrNotExist)
MkdirAll / RemoveAllidempotent; never feed RemoveAll unchecked input
Renameatomic in one file system on Unix; keep the temp file in the target directory
atomic writetemp file, Sync, Rename, directory Sync
ReadDir / WalkDirone level sorted / whole tree lexical, no symlink following
path vs filepathURLs and fs.FS names vs OS paths
traversalIsLocal/Localize for the name, os.Root for the access
fs.FSslash names, no ..; fs.Sub, fs.ReadFile, fstest.MapFS
embedpackage-relative, no .., no symlinks, all: for dotfiles; fs.Sub + http.FS
tempCreateTemp 0600, MkdirTemp 0700, t.TempDir() auto-clean
bufio.Scanner64 KiB limit, Buffer(buf, max), check Err()
bufio.WriterFlush and check its error
large filesio.Copy, SectionReader, streaming decoders
watchingfsnotify on the parent directory, debounce; or poll
umaskrequested bits &^ umask; Chmod is exact

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
os.Filehandle around an operating-system file descriptor
file descriptorsmall integer the kernel uses to track an open file
os.Openopen read-only
os.Createcreate or truncate and open read-write
os.OpenFileopen with chosen flags and permission bits
O_EXCLwith O_CREATE, fail if the name already exists
O_APPENDevery write goes to the current end of the file
O_TRUNCempty the file on open
FileModetype bits and permission bits of a file (fs.FileMode)
umaskprocess-wide mask removed from requested permission bits at creation
FileInfometadata returned by Stat: name, size, mode, mod time
DirEntrya directory listing entry with name and type, no stat needed
os.ReadFile / os.WriteFilewhole-file helpers; the write is not atomic
PathErrorerror type with Op, Path and Err for file operations
atomic renamename switch seen entirely or not at all by other processes
fsyncflush file data (or a directory) to stable storage
durabilitythe property that acknowledged data survives a crash
page cachekernel memory holding recently read and written file data
symlinkfile whose content is a path to another file
filepath.WalkDirrecursive walk in lexical order, not following symlinks
SkipDirreturn value that prunes a directory during a walk
pathslash-only path functions for URLs and fs.FS names
path/filepathOS-specific path functions for files on disk
filepath.Cleanlexical simplification of a path
filepath.Joinjoin elements and clean the result
filepath.Absabsolute form using the working directory
filepath.Relrelative path from a base to a target
filepath.Globfiles matching a shell-style pattern in one directory level
path traversalgetting a program to open a file outside the intended directory
filepath.IsLocallexical test that a name stays inside the directory it is joined to
filepath.Localizeconverts a slash path from untrusted input into a safe OS path
os.Rootdirectory handle whose operations cannot escape the directory (Go 1.24)
TOCTOUtime-of-check to time-of-use race between a check and the operation
io/fsread-only file system interfaces and helpers (Go 1.16)
fs.FSinterface with Open(name); names are slash-separated and unrooted
fs.ValidPathvalidates an fs.FS name
fs.Subfs.FS view of a subdirectory
fstest.MapFSin-memory fs.FS for tests
fstest.TestFSchecks that an fs.FS implementation follows the contract
go:embeddirective that embeds files into the binary at build time
embed.FSread-only file tree embedded in the binary
http.FSadapter from fs.FS to http.FileSystem
os.CreateTempcreate a unique private temp file (mode 0600)
os.MkdirTempcreate a unique private temp directory (mode 0700)
t.TempDirper-test directory removed automatically
bufio.Readerbuffered reader with ReadString, ReadBytes, Peek
bufio.Writerbuffered writer that needs Flush
bufio.Scannertoken reader with a size limit
token too longbufio.ErrTooLong, a token over the Scanner limit (64 KiB default)
Scanner.Buffersets the initial buffer and the maximum token size
ReadStringread up to and including a delimiter, no length limit
io.Copystream a reader into a writer with a reusable buffer
io.SectionReaderwindow over an io.ReaderAt
O_EXCL locklock file created exclusively; a convention, not enforced
flockadvisory file lock released by the kernel when the process dies
fsnotifythird-party package for file system change events
ReadLinkFSio/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.

Built by Morteza Negahi