Search code examples
gomultipart

Getting error when Parsing a multipart form in Go


I am trying to parse a multipart form in Go. I followed the tutorial for mimepart and still not able to get the NextPart. Please help.

Code:

package main

import (
    "fmt"
    "mime/multipart"
    "strings"
)


var testHead = `multipart/related; charset=utf-8; boundary="example-1"; type="text/xml"; start="<a@b.c>"`

var testBody3 = `--example-1
Content-Type: a/b
Content-ID: <a@b.c>
Life?
--example-1
Content-Type: b/c
Content-Transfer-Encoding: Base64
Content-ID: <b@c.d>
RG9uJ3QgdGFsayB0byBtZSBhYm91dCBsaWZlIQ==
--example-1--`

func main() {
    var boundary string
    var start string
    result := strings.Split(testHead, ";")
    for i := range result {
        if strings.Contains(result[i], "boundary=") {
            boundary = strings.Split(result[i], "boundary=")[1]
        }
        if strings.Contains(result[i], "start=") {
            start = strings.Split(result[i], "start=")[1]
        }
    }
    fmt.Println(start, boundary)

    r := strings.NewReader(testBody3)

    var nr *multipart.Reader = multipart.NewReader(r, boundary)
    fmt.Println("NEW READER ->", nr)

    p, err := nr.NextPart()
    fmt.Println(p, err)


}

Output:

"<a@b.c>" "example-1"    
NEW READER -> &{0xc04209a000 <nil> 0 [13 10] [13 10 45 45 34 101 120 97 109 112 108 101 45 49 34] [45 45 34 101 120 97 109 112 108 101 45 49 34 45 45] [45 45 34 101 120 97 109 112 108 101 45 49 34]}
<nil> multipart: NextPart: EOF

Solution

  • The issue is that your boundary is specified to be "example-1" when it should be example-1 (without quotes). You can parse content types by using mime.ParseMediaType.

    package main
    
    import (
        "fmt"
        "mime"
    )
    
    var testHead = `multipart/related; charset=utf-8; boundary="example-1"; type="text/xml"; start="<a@b.c>"`
    
    func main() {
        _, params, _ := mime.ParseMediaType(testHead)
        fmt.Println(params["boundary"])
    }