Skip to content

Commit 4064255

Browse files
committed
Updated attachment detection
1 parent 042ffb4 commit 4064255

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

attachment.go

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ type Attachment struct {
2626
meta AttachmentMeta
2727
}
2828

29+
const (
30+
defaultMimetype = "application/octet-stream"
31+
)
32+
2933
////////////////////////////////////////////////////////////////////////////////
3034
// LIFECYCLE
3135

@@ -56,10 +60,12 @@ func ReadAttachment(r io.Reader) (*Attachment, error) {
5660
////////////////////////////////////////////////////////////////////////////////
5761
// STRINGIFY
5862

63+
// Convert JSON into an attachment
5964
func (a *Attachment) UnmarshalJSON(data []byte) error {
6065
return json.Unmarshal(data, &a.meta)
6166
}
6267

68+
// Convert an attachment into JSON
6369
func (a *Attachment) MarshalJSON() ([]byte, error) {
6470
// Create a JSON representation
6571
var j struct {
@@ -77,6 +83,7 @@ func (a *Attachment) MarshalJSON() ([]byte, error) {
7783
return json.Marshal(j)
7884
}
7985

86+
// Stringify an attachment
8087
func (a *Attachment) String() string {
8188
data, err := json.MarshalIndent(a.meta, "", " ")
8289
if err != nil {
@@ -88,29 +95,46 @@ func (a *Attachment) String() string {
8895
////////////////////////////////////////////////////////////////////////////////
8996
// PUBLIC METHODS
9097

98+
// Return the filename of an attachment
9199
func (a *Attachment) Filename() string {
92100
return a.meta.Filename
93101
}
94102

103+
// Return the raw attachment data
95104
func (a *Attachment) Data() []byte {
96105
return a.meta.Data
97106
}
98107

108+
// Return the caption for the attachment
99109
func (a *Attachment) Caption() string {
100110
return a.meta.Caption
101111
}
102112

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
103116
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 == "" {
106119
return ""
107120
}
121+
108122
// 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 != "" {
111133
// Detect mimetype from extension
112134
mimetype = mime.TypeByExtension(filepath.Ext(a.meta.Filename))
113135
}
136+
137+
// Return the default mimetype
114138
return mimetype
115139
}
116140

0 commit comments

Comments
 (0)