-
Notifications
You must be signed in to change notification settings - Fork 0
/
image_url.go
executable file
·134 lines (103 loc) · 2.43 KB
/
image_url.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package imageurl
import (
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
)
// ImageURL ...
type ImageURL struct {
URI string
}
// Init ...
func Init() *ImageURL {
imageURL := &ImageURL{}
return imageURL
}
// SetURI ...
func SetURI(uri string) *ImageURL {
imageURL := &ImageURL{
URI: uri,
}
return imageURL
}
// GetFileName ...
func (i *ImageURL) GetFileName() string {
fileURL, _ := url.Parse(i.URI)
path := fileURL.Path
segments := strings.Split(path, "/")
fileName := segments[len(segments)-1]
return fileName
}
// GetImageType ...
func (i *ImageURL) GetImageType() ImageType {
client := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
}
resp, _ := client.Get(i.URI)
defer resp.Body.Close()
segments := strings.Split(resp.Header["Content-Type"][0], "/")
imageType := segments[len(segments)-1]
if segments := strings.Split(imageType, "+"); segments[0] == "svg" {
imageType = "svg"
}
if imageType == string(JPG) || imageType == string(JPEG) || imageType == string(PNG) || imageType == string(GIF) || imageType == string(BMP) || imageType == string(TIFF) || imageType == string(SVG) {
return ImageType(imageType)
}
return Unknown
}
// GetContentType ...
func (i *ImageURL) GetContentType() string {
client := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
}
resp, _ := client.Get(i.URI)
defer resp.Body.Close()
return resp.Header["Content-Type"][0]
}
// GetImageSize ...
func (i *ImageURL) GetImageSize() int32 {
client := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
}
resp, _ := client.Get(i.URI)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
return int32(len(body))
}
// SaveImage ...
func (i *ImageURL) SaveImage(dir string, fileName string) *os.File {
client := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
}
resp, _ := client.Get(i.URI)
defer resp.Body.Close()
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
panic(err)
}
path := filepath.Join(dir, fileName)
if file, err := os.Create(path); err != nil {
panic(err)
} else {
_, err := io.Copy(file, resp.Body)
if err != nil {
panic(err)
}
return file
}
}