Explorar o código

Adjusting trimReader to only trim whitespace on the first read. (#122)

Fixes #106
Jordan Wright %!s(int64=5) %!d(string=hai) anos
pai
achega
3f5bafa1cd
Modificáronse 2 ficheiros con 15 adicións e 8 borrados
  1. 12 5
      email.go
  2. 3 3
      email_test.go

+ 12 - 5
email.go

@@ -67,14 +67,21 @@ func NewEmail() *Email {
 // 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
+	rd      io.Reader
+	trimmed bool
 }
 
 // Read trims off any unicode whitespace from the originating reader
-func (tr trimReader) Read(buf []byte) (int, error) {
+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)
+	if err != nil {
+		return n, err
+	}
+	if !tr.trimmed {
+		t := bytes.TrimLeftFunc(buf[:n], unicode.IsSpace)
+		tr.trimmed = true
+		n = copy(buf, t)
+	}
 	return n, err
 }
 
@@ -83,7 +90,7 @@ func (tr trimReader) Read(buf []byte) (int, error) {
 // This function expects the data in RFC 5322 format.
 func NewEmailFromReader(r io.Reader) (*Email, error) {
 	e := NewEmail()
-	s := trimReader{rd: r}
+	s := &trimReader{rd: r}
 	tp := textproto.NewReader(bufio.NewReader(s))
 	// Parse the main headers
 	hdrs, err := tp.ReadMIMEHeader()

+ 3 - 3
email_test.go

@@ -94,7 +94,7 @@ func TestEmailWithHTMLAttachments(t *testing.T) {
 	//fmt.Println(string(b))
 
 	// TODO: Verify the attachments.
-	s := trimReader{rd: bytes.NewBuffer(b)}
+	s := &trimReader{rd: bytes.NewBuffer(b)}
 	tp := textproto.NewReader(bufio.NewReader(s))
 	// Parse the main headers
 	hdrs, err := tp.ReadMIMEHeader()
@@ -528,7 +528,7 @@ d-printable decoding.</div>
 	}
 }
 
-func TestAttachmentEmailFromReader (t *testing.T) {
+func TestAttachmentEmailFromReader(t *testing.T) {
 	ex := &Email{
 		Subject: "Test Subject",
 		To:      []string{"Jordan Wright <jmwright798@gmail.com>"},
@@ -592,7 +592,7 @@ TGV0J3MganVzdCBwcmV0ZW5kIHRoaXMgaXMgcmF3IEpQRUcgZGF0YS4=
 	if e.From != ex.From {
 		t.Fatalf("Incorrect \"From\": %#q != %#q", e.From, ex.From)
 	}
-	if len(e.Attachments) != 1  {
+	if len(e.Attachments) != 1 {
 		t.Fatalf("Incorrect number of attachments %d != %d", len(e.Attachments), 1)
 	}
 	if e.Attachments[0].Filename != a.Filename {