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" "bytes"
"fmt" "fmt"
"io" "io"
"mime"
"net/http" "net/http"
"strings" "strings"
@ -58,22 +59,15 @@ func downloadImage(client *http.Client, url string) (*bytes.Buffer, string, erro
if strings.Contains(contentType, "text/html") { if strings.Contains(contentType, "text/html") {
fileExtension = ".html" fileExtension = ".html"
} else { } else {
switch contentType { fileExtensions, err := mime.ExtensionsByType(contentType)
case "image/jpeg": if err != nil {
fileExtension = ".jpg" return nil, "", err
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)
} }
if fileExtensions == nil {
return nil, "", fmt.Errorf("fileExtensions is nil")
}
fileExtension = fileExtensions[0]
} }
// Save the image to a bytes.Buffer // Save the image to a bytes.Buffer