Go: Read a file section with an independent cursor
A parser may need one byte range from a larger source without moving that source’s sequential cursor. io.SectionReader provides a reader and seeker over a selected range of a ReaderAt. The section has its own position and returns EOF at its boundary.
Set up
Tested on Linux amd64 with Go 1.26.10. Use Bash with Go on your PATH, a text editor, and the mktemp, rm, and rmdir utilities. The example uses only the standard library. Keep the same terminal through cleanup, and stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as go-sectionreader-independent-cursor.go:
package main
import (
"fmt"
"io"
"strings"
)
func main() {
source := strings.NewReader("HEADpayloadTAIL")
if _, err := source.Seek(2, io.SeekStart); err != nil {
panic(err)
}
section := io.NewSectionReader(source, 4, 7)
body, err := io.ReadAll(section)
if err != nil {
panic(err)
}
fmt.Printf("section=%q size=%d\n", body, section.Size())
var one [1]byte
n, err := section.Read(one[:])
fmt.Printf("after section: bytes=%d eof=%t\n", n, err == io.EOF)
if _, err := section.Seek(0, io.SeekStart); err != nil {
panic(err)
}
var prefix [3]byte
if _, err := io.ReadFull(section, prefix[:]); err != nil {
panic(err)
}
fmt.Printf("rewound prefix=%q\n", prefix[:])
position, err := source.Seek(0, io.SeekCurrent)
if err != nil {
panic(err)
}
fmt.Printf("source cursor=%d\n", position)
short := io.NewSectionReader(strings.NewReader("abc"), 1, 5)
data, err := io.ReadAll(short)
if err != nil {
panic(err)
}
fmt.Printf("short source: declared=%d read=%d data=%q\n", short.Size(), len(data), data)
}Run:
go run go-sectionreader-independent-cursor.goObserved output:
section="payload" size=7
after section: bytes=0 eof=true
rewound prefix="pay"
source cursor=2
short source: declared=5 read=2 data="bc"Read the result
The section starts at byte offset four and exposes seven bytes. Reading it reaches its boundary without returning the trailing bytes. Seeking to zero rewinds relative to the section’s start, so the next three bytes are the beginning of the payload. The source’s sequential cursor stays at two.
The final case requests five bytes from a source with only two bytes available after the selected offset. Size reports the declared section length; it does not certify that the underlying data exists. io.ReadAll accepts EOF and returns those two bytes without an error. Compare the length with the expected size or use an exact-length read when truncation must fail.
Apply it carefully
This demonstration uses immutable strings and performs no file I/O. A file can implement the same ReaderAt interface, but the section does not own or close it. Keep the underlying source open until readers finish. A section is a view, not a snapshot: changes to an underlying file can affect later reads.
Validate externally supplied offsets and lengths, including arithmetic overflow, before constructing the section. Bound the size before reading the whole range into memory. A shared section’s sequential cursor also needs synchronization if multiple goroutines read or seek it; independent ranges can use separate section readers.
See NewSectionReader, SectionReader, and the ReaderAt contract.
Clean up
Remove the saved source and the empty scratch directory. Go manages its build cache separately. If the directory is not empty, inspect its contents before removing anything else.
rm -- go-sectionreader-independent-cursor.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.