...

Source file src/mime/multipart/example_test.go

Documentation: mime/multipart

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package multipart_test
     6  
     7  import (
     8  	"fmt"
     9  	"io"
    10  	"log"
    11  	"mime"
    12  	"mime/multipart"
    13  	"net/mail"
    14  	"strings"
    15  )
    16  
    17  func ExampleNewReader() {
    18  	msg := &mail.Message{
    19  		Header: map[string][]string{
    20  			"Content-Type": {"multipart/mixed; boundary=foo"},
    21  		},
    22  		Body: strings.NewReader(
    23  			"--foo\r\nFoo: one\r\n\r\nA section\r\n" +
    24  				"--foo\r\nFoo: two\r\n\r\nAnd another\r\n" +
    25  				"--foo--\r\n"),
    26  	}
    27  	mediaType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
    28  	if err != nil {
    29  		log.Fatal(err)
    30  	}
    31  	if strings.HasPrefix(mediaType, "multipart/") {
    32  		mr := multipart.NewReader(msg.Body, params["boundary"])
    33  		for {
    34  			p, err := mr.NextPart()
    35  			if err == io.EOF {
    36  				return
    37  			}
    38  			if err != nil {
    39  				log.Fatal(err)
    40  			}
    41  			slurp, err := io.ReadAll(p)
    42  			if err != nil {
    43  				log.Fatal(err)
    44  			}
    45  			fmt.Printf("Part %q: %q\n", p.Header.Get("Foo"), slurp)
    46  		}
    47  	}
    48  
    49  	// Output:
    50  	// Part "one": "A section"
    51  	// Part "two": "And another"
    52  }
    53  

View as plain text