Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use package mime to parse boundary #2

Merged
merged 3 commits into from
Feb 5, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
}