Files
Crussell/backend/internal/images/validate.go
T

35 lines
982 B
Go

package images
import (
"bytes"
"fmt"
)
var allowedImageMagic = []struct {
magic []byte
ext string
}{
{[]byte{0xff, 0xd8, 0xff}, ".jpg"},
{[]byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}, ".png"},
{[]byte{'G', 'I', 'F', '8', '7', 'a'}, ".gif"},
{[]byte{'G', 'I', 'F', '8', '9', 'a'}, ".gif"},
}
// ValidateImageBytes checks that data begins with a known image magic number
// and returns the appropriate file extension. Supports JPEG, PNG, WebP, and GIF.
func ValidateImageBytes(data []byte) (string, error) {
if len(data) < 12 {
return "", fmt.Errorf("file too small to be a valid image")
}
for _, m := range allowedImageMagic {
if bytes.HasPrefix(data, m.magic) {
return m.ext, nil
}
}
// WebP: bytes 0-3 = RIFF, bytes 8-11 = WEBP
if len(data) >= 12 && bytes.Equal(data[0:4], []byte("RIFF")) && bytes.Equal(data[8:12], []byte("WEBP")) {
return ".webp", nil
}
return "", fmt.Errorf("file is not a supported image type (jpeg, png, webp, gif)")
}