2022-11-19 18:43:56 +08:00
|
|
|
package getter
|
|
|
|
|
|
|
|
import (
|
2023-09-17 22:55:13 +08:00
|
|
|
"errors"
|
2022-11-19 18:43:56 +08:00
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Image struct {
|
|
|
|
Blob []byte
|
|
|
|
Mediatype string
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetImage(urlStr string) (*Image, error) {
|
|
|
|
if _, err := url.Parse(urlStr); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
response, err := http.Get(urlStr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
|
|
|
mediatype, err := getMediatype(response)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if !strings.HasPrefix(mediatype, "image/") {
|
2023-09-17 22:55:13 +08:00
|
|
|
return nil, errors.New("Wrong image mediatype")
|
2022-11-19 18:43:56 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
bodyBytes, err := io.ReadAll(response.Body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
image := &Image{
|
|
|
|
Blob: bodyBytes,
|
|
|
|
Mediatype: mediatype,
|
|
|
|
}
|
|
|
|
return image, nil
|
|
|
|
}
|