fix \r\n trim for multipart lines

This commit is contained in:
Adrien Marquès 2018-09-26 07:42:03 +02:00
parent 0974658bf2
commit ff9ff23e5a
2 changed files with 19 additions and 7 deletions

View File

@ -2,6 +2,8 @@ package multipart
import ( import (
"bufio" "bufio"
"fmt"
"io"
"strings" "strings"
) )
@ -85,8 +87,10 @@ func (comp *Component) read(_reader *bufio.Reader, _boundary string) error {
// 1. Stop on error // 1. Stop on error
if err != nil { if err != nil {
// remove last CR (newline) // remove last CR (newline)
if string(comp.Data[len(comp.Data)-1]) == "\n" { if strings.HasSuffix(string(comp.Data), "\n") {
comp.Data = comp.Data[0 : len(comp.Data)-1] comp.Data = comp.Data[0 : len(comp.Data)-1]
} else if strings.HasSuffix(string(comp.Data), "\r\n") {
comp.Data = comp.Data[0 : len(comp.Data)-2]
} }
return err return err
} }
@ -95,14 +99,22 @@ func (comp *Component) read(_reader *bufio.Reader, _boundary string) error {
if strings.HasPrefix(string(line), _boundary) { if strings.HasPrefix(string(line), _boundary) {
// remove last CR (newline) // remove last CR (newline)
if string(comp.Data[len(comp.Data)-1]) == "\n" { if strings.HasSuffix(string(comp.Data), "\n") {
comp.Data = comp.Data[0 : len(comp.Data)-1] comp.Data = comp.Data[0 : len(comp.Data)-1]
} else if strings.HasSuffix(string(comp.Data), "\r\n") {
comp.Data = comp.Data[0 : len(comp.Data)-2]
} }
// io.EOF if last boundary
if strings.Trim(string(line), " \t\r\n") == fmt.Sprintf("%s--", _boundary) {
return io.EOF
}
return nil return nil
} }
// 3. Ignore empty lines // 3. Ignore empty lines
if string(line) != "\n" && len(line) > 0 { if len(strings.Trim(string(line), " \t\r\n")) > 0 {
// add to header if not finished // add to header if not finished
if !headerRead { if !headerRead {

View File

@ -44,21 +44,21 @@ func (reader *Reader) Parse() error {
/* (1) For each component (until boundary) */ /* (1) For each component (until boundary) */
for { for {
mpd := &Component{ comp := &Component{
ContentType: "raw", ContentType: "raw",
Data: make([]byte, 0), Data: make([]byte, 0),
Headers: make(map[string]string), Headers: make(map[string]string),
} }
// 1. Read and parse data // 1. Read and parse data
err := mpd.read(reader.reader, reader.boundary) err := comp.read(reader.reader, reader.boundary)
// 3. Dispatch error // 3. Dispatch error
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
return err return err
} }
name := mpd.GetHeader("name") name := comp.GetHeader("name")
if len(name) < 1 { if len(name) < 1 {
return ErrMissingDataName return ErrMissingDataName
} }
@ -67,7 +67,7 @@ func (reader *Reader) Parse() error {
return ErrDataNameConflict return ErrDataNameConflict
} }
reader.Data[name] = mpd reader.Data[name] = comp
if err == io.EOF { if err == io.EOF {
return nil return nil