Last active
February 10, 2023 07:09
-
-
Save boaz0/d712a630048936f0be5c to your computer and use it in GitHub Desktop.
Detect compression type in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"log" | |
"net/http" | |
"os" | |
"strings" | |
) | |
func main() { | |
flag.Parse() | |
sourcefile := flag.Arg(0) | |
if sourcefile == "" { | |
log.Fatalln("Miss file argument") | |
} | |
file, err := os.Open(sourcefile) | |
if err != nil { | |
log.Fatalln(err.Error()) | |
} | |
defer file.Close() | |
buff := make([]byte, 512) | |
if _, err = file.Read(buff); err != nil { | |
log.Fatalln(err.Error()) | |
} | |
fileType := http.DetectContentType(buff) | |
log.Println("http--> ", fileType) | |
switch fileType { | |
case "application/x-gzip": | |
log.Println("gzip") | |
case "application/zip": | |
log.Println("zip") | |
default: | |
if strings.HasPrefix(string(buff), "\x42\x5a\x68") { | |
log.Println("bzip2") | |
} else { | |
log.Println("text") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment