Skip to content

Instantly share code, notes, and snippets.

@boaz0
Last active February 10, 2023 07:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boaz0/d712a630048936f0be5c to your computer and use it in GitHub Desktop.
Save boaz0/d712a630048936f0be5c to your computer and use it in GitHub Desktop.
Detect compression type in Golang
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