在go语言中判断一个文件的压缩方式:gzip或zip
Go  /  管理员 发布于 3个月前   89
判断文件是否压缩有很多种方式,比如:通过检查实际的数据字节、文件的扩展名等等。
下面将告诉你如何使用http.DetectContentType()函数来确定一个文件是否真的被压缩。
示例代码:
package main
import (
"flag"
"fmt"
"net/http"
"os"
)
func main() {
flag.Parse() //从命令行获取参数
sourcefile := flag.Arg(0)
// 打开一个你想检查的文件
// 如果它被压缩或不被压缩
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")
}
}
输出:
./detectzip testfile.sql
text/plain; charset=utf-8
文件没有被压缩
./detectzip testfile.unknown
应用/zip
文件是用gzip或zip压缩的
博主 在
2023年国务院办公厅春节放假通知:1月21日起休7天中评论 @ xiaoB 你只管努力,剩下的叫给天意;天若有情天亦老,..xiaoB 在
2023年国务院办公厅春节放假通知:1月21日起休7天中评论 会不会春节放假后又阳一次?..BUG4 在
你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事中评论 不是吧?..博主 在
go语言+beego框架中获取get,post请求的所有参数中评论 @ t1 直接在router.go文件中配就ok..Jade 在
如何在MySQL查询中获得当月记录中评论 Dear zongscan.com team, We can skyroc..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号