Add NewImageAttachment func
This commit is contained in:
@@ -1,5 +1,10 @@
|
||||
package activitystreams
|
||||
|
||||
import (
|
||||
"mime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
Type AttachmentType `json:"type"`
|
||||
URL string `json:"url"`
|
||||
@@ -10,3 +15,19 @@ type Attachment struct {
|
||||
type AttachmentType string
|
||||
|
||||
const AttachImage AttachmentType = "Image"
|
||||
|
||||
// NewImageAttachment creates a new Attachment from the given URL, setting the
|
||||
// correct type and automatically detecting the MediaType based on the file
|
||||
// extension.
|
||||
func NewImageAttachment(url string) *Attachment {
|
||||
var imgType string
|
||||
extIdx := strings.LastIndexByte(url, '.')
|
||||
if extIdx > -1 {
|
||||
imgType = mime.TypeByExtension(url[extIdx:])
|
||||
}
|
||||
return &Attachment{
|
||||
Type: AttachImage,
|
||||
URL: url,
|
||||
MediaType: imgType,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package activitystreams
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewImageAttachment(t *testing.T) {
|
||||
type args struct {
|
||||
url string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want *Attachment
|
||||
}{
|
||||
{name: "good svg", args: args{"https://writefreely.org/img/writefreely.svg"}, want: &Attachment{
|
||||
Type: "Image",
|
||||
URL: "https://writefreely.org/img/writefreely.svg",
|
||||
MediaType: "image/svg+xml",
|
||||
}},
|
||||
{name: "good png", args: args{"https://i.snap.as/12345678.png"}, want: &Attachment{
|
||||
Type: "Image",
|
||||
URL: "https://i.snap.as/12345678.png",
|
||||
MediaType: "image/png",
|
||||
}},
|
||||
{name: "no extension", args: args{"https://i.snap.as/12345678"}, want: &Attachment{
|
||||
Type: "Image",
|
||||
URL: "https://i.snap.as/12345678",
|
||||
MediaType: "",
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := NewImageAttachment(tt.args.url); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("NewImageAttachment() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user