-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathattachment.go
76 lines (66 loc) · 1.38 KB
/
attachment.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
package gostmark
import (
"encoding/base64"
"encoding/json"
"io"
"io/ioutil"
"sync"
)
type Attachment struct {
Name string
ContentType string
Reader io.Reader
ContentID string
contents string
sync.Mutex
}
// Return an attachment
func NewAttachment(name, contentType string, reader io.Reader) *Attachment {
return &Attachment{
Name: name,
ContentType: contentType,
Reader: reader,
}
}
// Contents returns the file contents. Currently
// non-streaming, and memory-caching, so hardly
// efficient.
func (a *Attachment) Contents() (string, error) {
a.Mutex.Lock()
if len(a.contents) == 0 {
b, e := ioutil.ReadAll(a.Reader)
if e != nil {
return "", e
} else {
b64 := base64.StdEncoding.EncodeToString(b)
a.contents = b64
}
}
a.Mutex.Unlock()
return a.contents, nil
}
// MarshalJSON exports the attachment as JSON
// for sending to the server
func (a *Attachment) MarshalJSON() ([]byte, error) {
fileContents, err := a.Contents()
if err != nil {
return []byte{}, err
}
packet := struct {
Name string
ContentType string
Content string
ContentID *string `json:",omitempty"`
}{
Name: a.Name,
ContentType: a.ContentType,
Content: string(fileContents),
}
// Content ID - omit if empty
if a.ContentID != "" {
// Copy
cid := a.ContentID
packet.ContentID = &cid
}
return json.Marshal(&packet)
}