Skip to content

Instantly share code, notes, and snippets.

@techjanitor
Last active August 29, 2015 14:07
Show Gist options
  • Save techjanitor/fc463789d84b89c07097 to your computer and use it in GitHub Desktop.
Save techjanitor/fc463789d84b89c07097 to your computer and use it in GitHub Desktop.
Check file signatures like libmagic
image, err := os.Open(imagefile)
if err != nil {
err = errors.New("problem opening file")
return
}
defer image.Close()
// Check file type
bytes := make([]byte, 4)
n, _ := image.ReadAt(bytes, 0)
if n < 4 {
os.RemoveAll(imagefile)
err = errors.New("unknown file type")
// PNG Signature
} else if bytes[0] == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4E && bytes[3] == 0x47 {
ext = ".png"
// JPG Signature
} else if bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF {
ext = ".jpg"
// Gif Signature
} else if bytes[0] == 0x47 && bytes[1] == 0x49 && bytes[2] == 0x46 && bytes[3] == 0x38 {
ext = ".gif"
// WebM Signature
} else if bytes[0] == 0x1A && bytes[1] == 0x45 && bytes[2] == 0xDF && bytes[3] == 0xA3 {
ext = ".webm"
} else {
os.RemoveAll(imagefile)
err = errors.New("unknown file type")
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment