Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
91: The io.Reader and io.Writer Interfaces
I've seen this mistake more times than I can count, usually in code reviews for engineers moving from languages where "reading a file" is a monolithic operation. You're trying to write a function that processes some data from a file, and your first instinct is to pass the file handle directly into your logic. It seems logical, right? But it creates a massive headache the moment you try to write a unit test.
package main
import (
"fmt"
"os"
)
// ProcessLog takes a file, reads its content, and counts lines.
func ProcessLog(f *os.File) (int, error) {
count := 0
buf := make([]byte, 1024)
for {
n, err := f.Read(buf)
if n > 0 {
// Imagine complex line-counting logic here
count++
}
if err != nil {
break
}
}
return count, nil
}
func main() {
f, _ := os.Open("app.log")
defer f.Close()
lines, _ := ProcessLog(f)
fmt.Printf("Found %d entries\n", lines)
}
The "Filesystem Lock" Problem
At first glance, the code above works perfectly. But here is where you'll hit a wall: how do you test ProcessLog? To test this function, you're forced to actually create a physical file on your hard drive, write some dummy data to it, call the function, and then delete the file. That's slow, it's brittle, and if your test crashes before the cleanup phase, you're leaving "junk" files all over your workspace.
The problem is that ProcessLog is too specific. It doesn't actually care that the data is coming from a file; it only cares that it can read bytes from something. By requiring *os.File, you've locked your logic to the filesystem.
Decoupling with io.Reader
In Go, we solve this using the io.Reader interface. If you look at the source code for os.File, you'll see that it has a Read method that matches the io.Reader signature. This means an *os.File is an io.Reader.
By changing the function signature to accept the interface instead of the concrete type, we unlock the ability to pass in anything that can be read—including strings, byte buffers, or network connections.
package main
import (
"bytes"
"fmt"
"io"
"os"
"strings"
)
// Now this accepts ANY reader. It doesn't know or care where the bytes come from.
func ProcessLog(r io.Reader) (int, error) {
count := 0
buf := make([]byte, 1024)
for {
n, err := r.Read(buf)
if n > 0 {
count++
}
if err == io.EOF {
break
}
if err != nil {
return 0, err
}
}
return count, nil
}
func main() {
// Production: still works with files!
f, _ := os.Open("app.log")
defer f.Close()
ProcessLog(f)
// Testing: now we can use a simple string!
testData := "line1\nline2\nline3"
reader := strings.NewReader(testData)
count, _ := ProcessLog(reader)
fmt.Printf("Test found %d entries\n", count)
}
Why this makes your code flexible
Notice what happened in the fix. I replaced *os.File with io.Reader. Suddenly, strings.NewReader (which returns a *strings.Reader) and bytes.NewBuffer both work. I can now write 50 different unit tests with 50 different edge-case strings without ever touching the hard drive.
This is the "Go way" of handling data streams. You define your functions based on what they do with the data, not where the data lives.
Symmetry with io.Writer
The same philosophy applies to output. You'll often see functions that take an io.Writer. If you write a function that takes *os.File to save a report, you're stuck with files. But if you take an io.Writer, your function can write to a file, a network socket (like an HTTP response), or a bytes.Buffer for testing.
I always tell my juniors: whenever you're tempted to pass a file or a connection into a function, stop and ask yourself, "Do I actually need the file's metadata (like permissions or size), or do I just need to read/write bytes?" If it's the latter, use io.Reader or io.Writer. Every single time.
📋 Practical Task
Build a Generic Data Transformer
You need to build a tool that takes a stream of text, converts it to uppercase, and writes it to an output stream. To ensure this is testable, you must not use any concrete file types in your logic.
Requirements:
- Create a function called
TransformToUpper(r io.Reader, w io.Writer) error. - The function should read from
rand write the uppercase version of that data tow. (Hint:bytes.ToUpperorstrings.ToUpperwill be useful here). - In your
mainfunction, demonstrate that this works by using astrings.Readeras the input and abytes.Bufferas the output. - Print the final contents of the buffer to the console to verify the transformation.
There are no comments for now.