duannan3959 2018-11-08 20:17
浏览 103
已采纳

multipart.NewReader后无输出

This is probably incredibly simple but no amount of Googling has surfaced an answer so far. Nearly 100% of the code is from the docs here: https://golang.org/pkg/mime/multipart/#example_NewReader

The problem is I can't print anything after the for loop and I tried closing whatever needs closing (see commented code) but can't figure out what that is.

  package main

    import (
    "fmt"
    "io"
    "io/ioutil"
    "log"
    "mime"
    "mime/multipart"
    "net/mail"
    "strings"
)

func main() {
    msg := &mail.Message{
        Header: map[string][]string{
            "Content-Type": {"multipart/mixed; boundary=foo"},
        },
        Body: strings.NewReader(
            "--foo
Foo: one

A section
" +
                "--foo
Foo: two

And another
" +
                "--foo--
"),
    }
    mediaType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
    if err != nil {
        log.Fatal(err)
    }
    if strings.HasPrefix(mediaType, "multipart/") {
        mr := multipart.NewReader(msg.Body, params["boundary"])
        for {
            p, err := mr.NextPart()
            if err == io.EOF {
                return
            }
            if err != nil {
                log.Fatal(err)
            }
            slurp, err := ioutil.ReadAll(p)
            if err != nil {
                log.Fatal(err)
            }
            fmt.Printf("Part %q: %q
", p.Header.Get("Foo"), slurp)
            // p.Close()

        }
        // mr.Close()
        // mr.Interface().(io.Closer).Close()
        // ioutil.NopCloser(mr)

    }

    // This does not print
    fmt.Printf("Test: %s
", "asdfasdf")
    fmt.Println("Test")

}

What am I missing? How would I attack the problem of tracking down what I'm missing?

  • 写回答

1条回答 默认 最新

  • dongzhang6544 2018-11-08 20:21
    关注

    You currently have no way of getting out of the for without returning, which will make you get out of the function as well. Looks like you want to change

     if err == io.EOF {
         return
     }
    

    to

     if err == io.EOF {
         break
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?