forked from emersion/go-message
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entity.go
98 lines (83 loc) · 2.38 KB
/
entity.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package message
import (
"bufio"
"io"
"mime/multipart"
"net/textproto"
"strings"
"github.com/emersion/go-message/charset"
)
// An Entity is either a message or a one of the parts in the body of a
// multipart entity.
type Entity struct {
Header Header // The entity's header.
Body io.Reader // The decoded entity's body.
mediaType string
mediaParams map[string]string
}
// NewEntity makes a new Entity with the provided header and body. The entity's
// encoding and charset are automatically decoded to UTF-8.
func NewEntity(header Header, body io.Reader) *Entity {
body = encodingReader(header.Get("Content-Transfer-Encoding"), body)
mediaType, mediaParams, _ := header.ContentType()
if ch, ok := mediaParams["charset"]; ok {
if converted, err := charset.Reader(ch, body); err == nil {
body = converted
}
}
return &Entity{
Header: header,
Body: body,
mediaType: mediaType,
mediaParams: mediaParams,
}
}
// NewMultipart makes a new multipart Entity with the provided header and parts.
// The Content-Type header must begin with "multipart/".
func NewMultipart(header Header, parts []*Entity) *Entity {
r := &multipartBody{
header: header,
parts: parts,
}
return NewEntity(header, r)
}
// Read reads a message from r. The message's encoding and charset are
// automatically decoded to UTF-8.
func Read(r io.Reader) (*Entity, error) {
br := bufio.NewReader(r)
h, err := textproto.NewReader(br).ReadMIMEHeader()
if err != nil {
return nil, err
}
return NewEntity(Header(h), br), nil
}
// MultipartReader returns a MultipartReader that reads parts from this entity's
// body. If this entity is not multipart, it returns nil.
func (e *Entity) MultipartReader() MultipartReader {
if !strings.HasPrefix(e.mediaType, "multipart/") {
return nil
}
if mb, ok := e.Body.(*multipartBody); ok {
return mb
}
return &multipartReader{multipart.NewReader(e.Body, e.mediaParams["boundary"])}
}
// writeBodyTo writes this entity's body to w (without the header).
func (e *Entity) writeBodyTo(w *Writer) error {
var err error
if mb, ok := e.Body.(*multipartBody); ok {
err = mb.writeBodyTo(w)
} else {
_, err = io.Copy(w, e.Body)
}
return err
}
// WriteTo writes this entity's header and body to w.
func (e *Entity) WriteTo(w io.Writer) error {
ew, err := CreateWriter(w, e.Header)
if err != nil {
return err
}
defer ew.Close()
return e.writeBodyTo(ew)
}