Read A Window With io.SectionReader
Expose one byte range of a ReaderAt as its own reader with io.NewSectionReader, so Size and Seek are window relative and the source offset never moves.
Code
package main
import (
"bytes"
"encoding/binary"
"fmt"
"io"
)
func main() {
// 8 条 big-endian uint16 记录拼成的顺序文件
raw := make([]byte, 0, 16)
for _, v := range []uint16{10, 20, 30, 40, 50, 60, 70, 80} {
raw = binary.BigEndian.AppendUint16(raw, v)
}
file := bytes.NewReader(raw)
// 窗口:从第 4 字节起、长度 8 字节,即 30/40/50/60 四条记录
window := io.NewSectionReader(file, 4, 8)
fmt.Println("window size:", window.Size())
buf := make([]byte, 2)
for i := 0; ; i++ {
if _, err := io.ReadFull(window, buf); err != nil {
fmt.Println("stop after", i, "records:", err)
break
}
fmt.Printf("record %d: %d\n", i, binary.BigEndian.Uint16(buf))
}
// Seek 相对窗口起点,不是文件起点
if _, err := window.Seek(2, io.SeekStart); err != nil {
panic(err)
}
if _, err := io.ReadFull(window, buf); err != nil {
panic(err)
}
fmt.Println("second record of window:", binary.BigEndian.Uint16(buf))
// 窗口读的是 ReadAt:底层 reader 自己的读偏移没被动过
first, err := file.ReadByte()
fmt.Println("first byte of the file:", first, err)
}What the code does
Everything runs inside func main — no types, no helpers, just the fixture setup, the window, the read loop, one seek and one more read.
The only repetition is the fixture loop for _, v := range []uint16{10, 20, 30, 40, 50, 60, 70, 80}; after that the file runs straight through. Of the 3 if err != nil branches, the loop’s io.ReadFull check is the expected exit — a drained window prints stop after and breaks — while the Seek and second ReadFull checks end in panic(err).
Watch out for
- Imports are all standard library:
bytes,encoding/binary,fmt,io. - To reuse this window logic in a library, return the error from the
SeekandReadFullcalls instead ofpanic(err)— the loop’s EOF exit already shows the non-fatal shape.
Applying it
The window itself is one call: io.NewSectionReader(file, 4, 8) — offset 4, length 8, covering records 30/40/50/60.
Output lines carry their own labels — window size:, stop after, record N: — so each line names the step that printed it.
Statements that matter most here
for _, v := range []uint16{10, 20, 30, 40, 50, 60, 70, 80} {
raw = binary.BigEndian.AppendUint16(raw, v)
}
raw := make([]byte, 0, 16)
buf := make([]byte, 2)
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- Through `panic(err)` — the 3 checkpoints test `err` and abort the run on the first non-nil one.
- What does Read A Window With io.SectionReader print when run?
- Running the file directly is enough — expect labeled output lines such as `window size:`, `stop after`, `record`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.