Skip to content

Commit

Permalink
Merge pull request #2 from internavenue/master
Browse files Browse the repository at this point in the history
use package mime to parse boundary
  • Loading branch information
ian-kent committed Feb 5, 2015
2 parents f1c5d35 + 6a26f27 commit d0150aa
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
24 changes: 17 additions & 7 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"crypto/rand"
"encoding/base64"
"log"
"regexp"
"mime"
"strings"
"time"
)
Expand Down Expand Up @@ -116,14 +116,14 @@ func (content *Content) ParseMIMEBody() *MIMEBody {

if hdr, ok := content.Headers["Content-Type"]; ok {
if len(hdr) > 0 {
re := regexp.MustCompile("boundary=\"([^\"]+)\"")
match := re.FindStringSubmatch(hdr[0])
if len(match) < 2 {
boundary := extractBoundary(hdr[0])
var p []string
if len(boundary) > 0 {
p = strings.Split(content.Body, "--"+boundary)
log.Printf("Got boundary: %s", boundary)
} else {
log.Printf("Boundary not found: %s", hdr[0])
}
log.Printf("Got boundary: %s", match[1])

p := strings.Split(content.Body, "--"+match[1])

for _, s := range p {
if len(s) > 0 {
Expand Down Expand Up @@ -204,3 +204,13 @@ func ContentFromString(data string) *Content {
Body: x[0],
}
}

// extractBoundary extract boundary string in contentType.
// It returns empty string if no valid boundary found
func extractBoundary(contentType string) string {
_, params, err := mime.ParseMediaType(contentType)
if err == nil {
return params["boundary"]
}
return ""
}
27 changes: 27 additions & 0 deletions message_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package data

import (
"testing"
)

func TestExtractBoundary(t *testing.T) {
contents := []struct {
content string
expect string
}{
{
`multipart/alternative; boundary="_----------=_MCPart_498914860"`,
`_----------=_MCPart_498914860`,
},
{
`multipart/alternative; boundary=047d7bd74a2049b624050d805118`,
`047d7bd74a2049b624050d805118`,
},
}

for _, c := range contents {
if b := extractBoundary(c.content); b != c.expect {
t.Fatal("extractBoundary expect", c.expect, "but get", b)
}
}
}

0 comments on commit d0150aa

Please sign in to comment.