go / intermediate
Snippet
Intercepting Streams Using a Custom io.Reader Decorator
Go's standard library relies heavily on interfaces like io.Reader. By wrapping an existing io.Reader inside a custom struct and implementing the Read([]byte) (int, error) method, you can perform streaming data transformations on the fly without loading the entire dataset into memory.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package mainimport ("fmt""io""strings")type UpperReader struct {reader io.Reader}func NewUpperReader(r io.Reader) *UpperReader {return &UpperReader{reader: r}}func (ur *UpperReader) Read(p []byte) (int, error) {n, err := ur.reader.Read(p)for i := 0; i < n; i++ {if p[i] >= 'a' && p[i] <= 'z' {p[i] = p[i] - 32}}return n, err}func main() {input := strings.NewReader("hello, world!")upper := NewUpperReader(input)buf := make([]byte, 13)_, _ = io.ReadFull(upper, buf)fmt.Println(string(buf))}
Breakdown
1
type UpperReader struct {
Defines a struct that wraps an inner io.Reader interface.
2
func (ur *UpperReader) Read(p []byte) (int, error) {
Implements the io.Reader interface, intercepting reads to modify the read buffer data.
3
n, err := ur.reader.Read(p)
Reads data from the underlying reader into the slice p, obtaining the number of bytes read.
4
p[i] = p[i] - 32
Mutates the read bytes in-place to convert lowercase ASCII characters to uppercase.