Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created February 1, 2019 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/51d03e196fd58e82fe66f8841a48dd4c to your computer and use it in GitHub Desktop.
Save xeoncross/51d03e196fd58e82fe66f8841a48dd4c to your computer and use it in GitHub Desktop.
just some examples of Golang io.Reader which trim whitespace
type TrimReader2 struct{ io.Reader }
var trailingws = regexp.MustCompile(` *\r?\n`)
func (tr TrimReader2) Read(bs []byte) (int, error) {
// Perform the requested read on the given reader.
n, err := tr.Reader.Read(bs)
if err != nil {
return n, err
}
// Remove trailing whitespace from each line.
lines := string(bs[:n])
trimmed := []byte(trailingws.ReplaceAllString(lines, ""))
copy(bs, trimmed)
return len(trimmed), nil
}
// trimReader is a custom io.Reader that will trim any leading
// whitespace, as this can cause email imports to fail.
type trimReader struct {
rd io.Reader
}
// Read trims off any unicode whitespace from the originating reader
func (tr trimReader) Read(buf []byte) (int, error) {
n, err := tr.rd.Read(buf)
t := bytes.TrimLeftFunc(buf[:n], unicode.IsSpace)
n = copy(buf, t)
return n, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment