@@ -26,6 +26,10 @@ type Attachment struct {
26
26
meta AttachmentMeta
27
27
}
28
28
29
+ const (
30
+ defaultMimetype = "application/octet-stream"
31
+ )
32
+
29
33
////////////////////////////////////////////////////////////////////////////////
30
34
// LIFECYCLE
31
35
@@ -56,10 +60,12 @@ func ReadAttachment(r io.Reader) (*Attachment, error) {
56
60
////////////////////////////////////////////////////////////////////////////////
57
61
// STRINGIFY
58
62
63
+ // Convert JSON into an attachment
59
64
func (a * Attachment ) UnmarshalJSON (data []byte ) error {
60
65
return json .Unmarshal (data , & a .meta )
61
66
}
62
67
68
+ // Convert an attachment into JSON
63
69
func (a * Attachment ) MarshalJSON () ([]byte , error ) {
64
70
// Create a JSON representation
65
71
var j struct {
@@ -77,6 +83,7 @@ func (a *Attachment) MarshalJSON() ([]byte, error) {
77
83
return json .Marshal (j )
78
84
}
79
85
86
+ // Stringify an attachment
80
87
func (a * Attachment ) String () string {
81
88
data , err := json .MarshalIndent (a .meta , "" , " " )
82
89
if err != nil {
@@ -88,29 +95,46 @@ func (a *Attachment) String() string {
88
95
////////////////////////////////////////////////////////////////////////////////
89
96
// PUBLIC METHODS
90
97
98
+ // Return the filename of an attachment
91
99
func (a * Attachment ) Filename () string {
92
100
return a .meta .Filename
93
101
}
94
102
103
+ // Return the raw attachment data
95
104
func (a * Attachment ) Data () []byte {
96
105
return a .meta .Data
97
106
}
98
107
108
+ // Return the caption for the attachment
99
109
func (a * Attachment ) Caption () string {
100
110
return a .meta .Caption
101
111
}
102
112
113
+ // Return the mime media type for the attachment, based
114
+ // on the data and/or filename extension. Returns an empty string if
115
+ // there is no data or filename
103
116
func (a * Attachment ) Type () string {
104
- // If there's no data, return empty
105
- if len (a .meta .Data ) == 0 {
117
+ // If there's no data or filename , return empty
118
+ if len (a .meta .Data ) == 0 && a . meta . Filename == "" {
106
119
return ""
107
120
}
121
+
108
122
// Mimetype based on content
109
- mimetype := http .DetectContentType (a .meta .Data )
110
- if mimetype == "application/octet-stream" && a .meta .Filename != "" {
123
+ mimetype := defaultMimetype
124
+ if len (a .meta .Data ) > 0 {
125
+ mimetype = http .DetectContentType (a .meta .Data )
126
+ if mimetype != defaultMimetype {
127
+ return mimetype
128
+ }
129
+ }
130
+
131
+ // Mimetype based on filename
132
+ if a .meta .Filename != "" {
111
133
// Detect mimetype from extension
112
134
mimetype = mime .TypeByExtension (filepath .Ext (a .meta .Filename ))
113
135
}
136
+
137
+ // Return the default mimetype
114
138
return mimetype
115
139
}
116
140
0 commit comments