在Go中解析多部分表单时出错

时间:2018-02-01 07:36:46

标签: go multipart

我正在尝试解析Go中的多部分表单。我按照mimepart的教程进行操作,仍无法获得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) } 。请帮忙。

代码:

"<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

输出:

NHibernate

1 个答案:

答案 0 :(得分:2)

问题是,当您的边界应为"example-1"(没有引号)时,您的边界被指定为example-1。您可以使用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"])
}