Custom io.Reader Transforms Uppercase

A custom io.Reader wraps another reader and rewrites each filled buffer in place, passing byte counts and EOF straight through so ReadAll composes.

GoData Fetching

Code

gosnippet
32 lines
package main

import (
	"fmt"
	"io"
	"strings"
)

// upperReader 包装底层 Reader,把读到的 ASCII 字母就地转成大写
type upperReader struct {
	r io.Reader
}

func (u upperReader) Read(p []byte) (int, error) {
	n, err := u.r.Read(p)
	// 只改写本次真正读到的 n 个字节;字节数与 io.EOF 原样透传
	for i := 0; i < n; i++ {
		if p[i] >= 'a' && p[i] <= 'z' {
			p[i] -= 'a' - 'A'
		}
	}
	return n, err
}

func main() {
	src := strings.NewReader("milk way 42")
	var r io.Reader = upperReader{r: src}

	// io.ReadAll 反复调用 Read,直到返回 io.EOF
	all, err := io.ReadAll(r)
	fmt.Printf("%q %v\n", string(all), err)
}

What this snippet does

The active pieces are the functions Read and main.

The loop for i := 0; i < n; i++ is the only repeated construct.

Points of care

  • No install step: every API used ships with the platform.

Applying it

The top-level signature is: func (u upperReader) Read(p []byte) (int, error)

Statements that matter

func (u upperReader) Read(p []byte) (int, error) {
	n, err := u.r.Read(p)
	// 只改写本次真正读到的 n 个字节;字节数与 io.EOF 原样透传
	for i := 0; i < n; i++ {
		if p[i] >= 'a' && p[i] <= 'z' {
			p[i] -= 'a' - 'A'
		}
	}
	return n, err
}
func main() {
	src := strings.NewReader("milk way 42")
	var r io.Reader = upperReader{r: src}
	// io.ReadAll 反复调用 Read,直到返回 io.EOF
	all, err := io.ReadAll(r)
	fmt.Printf("%q %v\n", string(all), err)
}

Interactive Tools for This Topic

FAQ

How do you run Custom io.Reader Transforms Uppercase?
The runtime alone is enough: execute the file as a complete program.