Improve contentType parsing in downloadImage()

This commit is contained in:
Yang Luo 2023-08-19 02:35:45 +08:00
parent fec54944dd
commit a07216d0e1

View File

@ -18,6 +18,7 @@ import (
"bytes"
"fmt"
"io"
"mime"
"net/http"
"strings"
@ -58,22 +59,15 @@ func downloadImage(client *http.Client, url string) (*bytes.Buffer, string, erro
if strings.Contains(contentType, "text/html") {
fileExtension = ".html"
} else {
switch contentType {
case "image/jpeg":
fileExtension = ".jpg"
case "image/png":
fileExtension = ".png"
case "image/gif":
fileExtension = ".gif"
case "image/vnd.microsoft.icon":
fileExtension = ".ico"
case "image/x-icon":
fileExtension = ".ico"
case "image/svg+xml":
fileExtension = ".svg"
default:
return nil, "", fmt.Errorf("unsupported content type: %s", contentType)
fileExtensions, err := mime.ExtensionsByType(contentType)
if err != nil {
return nil, "", err
}
if fileExtensions == nil {
return nil, "", fmt.Errorf("fileExtensions is nil")
}
fileExtension = fileExtensions[0]
}
// Save the image to a bytes.Buffer