Golang : How to tell if a file is compressed either gzip or zip ?
Sometimes it is good to check if a file is really in compressed form or not by examining the actual data bytes and not relying on the file extension alone. This tutorial will show you how to use http.DetectContentType() function to determine if a file is really compressed or not.
Here are the codes:
package main
import (
"flag"
"fmt"
"net/http"
"os"
)
func main() {
flag.Parse() // get the arguments from command line
sourcefile := flag.Arg(0)
// open a file that you wish to check
// if it is compressed or not
if sourcefile == "" {
fmt.Println("Usage : detectcompress sourcefile")
os.Exit(1)
}
file, err := os.Open(sourcefile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer file.Close()
buff := make([]byte, 512)
// why 512 bytes ? see http://golang.org/pkg/net/http/#DetectContentType
_, err = file.Read(buff)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
filetype := http.DetectContentType(buff)
fmt.Println(filetype) // for info
switch filetype {
case "application/x-gzip", "application/zip":
fmt.Println("File is compressed with gzip or zip")
default:
fmt.Println("File is not compressed")
}
}
Sample output :
./detectzip testfile.sql
text/plain; charset=utf-8
File is not compressed
./detectzip testfile.unknown
application/zip
File is compressed with gzip or zip
Reference :
See also : Golang : How to verify uploaded file is image or allowed file types
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+19.9k Golang : GORM create record or insert new record into database example
+8k Golang : Generate random Chinese, Japanese, Korean and other runes
+4.6k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+13.8k Golang : How to check for empty array string or string?
+8.5k Golang : Format strings to SEO friendly URL example
+22.9k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+5.1k Golang : Dealing with backquote
+5.9k Golang : constant 20013 overflows byte error message
+6.1k Nginx : How to block user agent ?
+9.1k Golang : Convert file content to Hex
+4.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+5.2k Golang : Create new color from command line parameters