-
Notifications
You must be signed in to change notification settings - Fork 173
/
factory.go
76 lines (63 loc) · 1.7 KB
/
factory.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 image
import (
"bytes"
"context"
"io"
"net/url"
"github.com/pkg/errors"
"github.com/thoas/picfit/constants"
"github.com/thoas/picfit/http"
storagepkg "github.com/thoas/picfit/storage"
)
// FromURL retrieves an ImageFile from an url
func FromURL(ctx context.Context, u *url.URL, userAgent string) (*ImageFile, error) {
storage := storagepkg.NewHTTPStorage(nil, http.NewClient(http.WithUserAgent(userAgent)))
content, err := storage.OpenFromURL(ctx, u)
if err != nil {
return nil, errors.WithStack(err)
}
headers, err := storage.HeadersFromURL(u)
if err != nil {
return nil, errors.WithStack(err)
}
var buffer bytes.Buffer
if _, err = io.Copy(&buffer, content); err != nil {
return nil, errors.WithStack(err)
}
if err := content.Close(); err != nil {
return nil, errors.WithStack(err)
}
return &ImageFile{
Source: buffer.Bytes(),
Headers: headers,
Filepath: u.Path[1:],
}, nil
}
// FromStorage retrieves an ImageFile from storage
func FromStorage(ctx context.Context, storage *storagepkg.Storage, filepath string) (*ImageFile, error) {
var file *ImageFile
var err error
f, stat, err := storage.OpenWithStat(ctx, filepath)
if err != nil {
return nil, errors.WithStack(err)
}
file = &ImageFile{
Filepath: filepath,
Storage: storage,
}
contentType := file.ContentType()
headers := map[string]string{
"Last-Modified": stat.ModifiedTime.Format(constants.ModifiedTimeFormat),
"Content-Type": contentType,
}
var buffer bytes.Buffer
if _, err = io.Copy(&buffer, f); err != nil {
return nil, errors.WithStack(err)
}
file.Source = buffer.Bytes()
file.Headers = headers
if err := f.Close(); err != nil {
return nil, errors.WithStack(err)
}
return file, err
}