forked from noelyahan/impexp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
url.go
63 lines (56 loc) · 1.16 KB
/
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
package impexp
import (
"errors"
"fmt"
"image"
"image/jpeg"
"image/png"
"net/http"
"net/url"
"strings"
)
type httpURL struct {
url string
}
// NewURLImporter uses to import jpg, png images from given url
func NewURLImporter(url string) Importer {
return httpURL{url}
}
func (o httpURL) Import() (image.Image, error) {
errMsg := fmt.Sprintf("impexp can't find the file or file is invalid %s", o.url)
if !isValidURL(o.url) {
return nil, fmt.Errorf("impexp found a invalid URL: %s", o.url)
}
resp, err := http.Get(o.url)
if err != nil {
return nil, errors.New(errMsg)
}
defer func() {
if resp != nil {
resp.Body.Close()
}
}()
reader := resp.Body
cType := resp.Header.Get("Content-Type")
cType = strings.Replace(cType, "/", ".", -1)
ext := getExt(cType)
var img image.Image
if ext == "jpg" || ext == "jpeg" {
img, err = jpeg.Decode(reader)
} else if ext == "png" {
img, err = png.Decode(reader)
} else {
return nil, errors.New(errMsg)
}
if err != nil {
return nil, errors.New(errMsg)
}
return img, nil
}
func isValidURL(toTest string) bool {
_, err := url.ParseRequestURI(toTest)
if err != nil {
return false
}
return true
}