go / intermediate
Snippet
Implementing a custom decorator using io.Reader
This snippet demonstrates the decorator pattern using Go's standard io.Reader interface. By wrapping an existing io.Reader, we can intercept and transform data during the read operation, modifying lowercase characters to uppercase inline without allocating additional memory buffers.
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() {r := NewUpperReader(strings.NewReader("hello reader"))buf := make([]byte, 32)n, _ := r.Read(buf)fmt.Println(string(buf[:n]))}
Breakdown
1
type UpperReader struct {
Declares a struct that embeds an existing io.Reader interface.
2
func (ur *UpperReader) Read(p []byte) (int, error) {
Implements the io.Reader interface method to fetch and modify content.
3
p[i] = p[i] - 32
Converts lowercase ASCII characters to uppercase directly inside the buffer.