package mainimport ( "io" "os" "strings" "fmt")type rot13Reader struct { r io.Reader}func (rot13 rot13Reader)Read(p []byte) (n int, err error){ n,err = rot13.r.Read(p) for i := 0; i < len(p); i++ { if (p[i] >= ‘A‘ && p[i] < ‘N‘) || (p[i] >=‘a‘ && p[i] < ‘n‘) { p[i] += 13 } else if (p[i] > ‘M‘ && p[i] <= ‘Z‘) || (p[i] > ‘m‘ && p[i] <= ‘z‘){ p[i] -= 13 } } return}func main() { s := strings.NewReader( "Lbh penpxrq gur pbqr!") r := rot13Reader{s} fmt.Println(r) io.Copy(os.Stdout, &r)}
Go official tutorial answer address https://gist.github.com/zyxar/2317744
A common pattern is an IO. Reader that wraps anotherio.Reader, Modifying the stream in some way.
For example, the gzip. newreader function takesio.Reader(A stream of gzipped data) and returns*gzip.ReaderThat also implementsio.Reader(A stream of the decompressed data ).
Implementrot13ReaderThat implementsio.ReaderAnd reads fromio.Reader, Modifying the stream by applying the rot13 substitution cipher to all alphabetical characters.
Therot13ReaderType is provided for you. Make itio.ReaderBy implementing itsReadMethod.
Exercise: rot13 Reader