Created
February 1, 2019 23:07
-
-
Save xeoncross/51d03e196fd58e82fe66f8841a48dd4c to your computer and use it in GitHub Desktop.
just some examples of Golang io.Reader which trim whitespace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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