1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add IsLink, FileMode, MiMeType funcs for file

This commit is contained in:
dudaodong
2022-01-06 16:53:32 +08:00
parent 86d4b25a2b
commit eeff28606e
3 changed files with 107 additions and 0 deletions

1
.gitignore vendored
View File

@@ -4,5 +4,6 @@
cryptor/*.txt
fileutil/*.txt
fileutil/*.zip
fileutil/*.link
fileutil/unzip/*
cryptor/*.pem

View File

@@ -9,7 +9,9 @@ import (
"bufio"
"errors"
"io"
"io/fs"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
@@ -240,3 +242,57 @@ func UnZip(zipFile string, destPath string) error {
}
return nil
}
// IsLink checks if a file is symbol link or not
func IsLink(path string) bool {
fi, err := os.Lstat(path)
if err != nil {
return false
}
return fi.Mode()&os.ModeSymlink != 0
}
// FileMode return file's mode and permission
func FileMode(path string) (fs.FileMode, error) {
fi, err := os.Lstat(path)
if err != nil {
return 0, err
}
return fi.Mode(), nil
}
// MiMeType return file mime type
// file should be string or *os.File
func MiMeType(file interface{}) string {
var mediatype string
readBuffer := func(f *os.File) ([]byte, error) {
buffer := make([]byte, 512)
_, err := f.Read(buffer)
if err != nil {
return nil, err
}
return buffer, nil
}
if filePath, ok := file.(string); ok {
f, err := os.Open(filePath)
if err != nil {
return mediatype
}
buffer, err := readBuffer(f)
if err != nil {
return mediatype
}
return http.DetectContentType(buffer)
}
if f, ok := file.(*os.File); ok {
buffer, err := readBuffer(f)
if err != nil {
return mediatype
}
return http.DetectContentType(buffer)
}
return mediatype
}

View File

@@ -181,3 +181,53 @@ func TestZipAndUnZip(t *testing.T) {
os.Remove(zipFile)
os.RemoveAll(unZipPath)
}
func TestFileMode(t *testing.T) {
srcFile := "./text.txt"
CreateFile(srcFile)
mode, err := FileMode(srcFile)
if err != nil {
t.Fail()
}
t.Log(mode)
os.Remove(srcFile)
}
func TestIsLink(t *testing.T) {
srcFile := "./text.txt"
CreateFile(srcFile)
linkFile := "./text.link"
if !IsExist(linkFile) {
_ = os.Symlink(srcFile, linkFile)
}
if !IsLink(linkFile) {
internal.LogFailedTestInfo(t, "IsLink", linkFile, "true", "false")
t.FailNow()
}
if IsLink("./file.go") {
internal.LogFailedTestInfo(t, "IsLink", "./file.go", "false", "true")
t.FailNow()
}
os.Remove(srcFile)
os.Remove(linkFile)
}
func TestMiMeType(t *testing.T) {
mt1 := MiMeType("./file.go")
expected := "text/plain; charset=utf-8"
if mt1 != expected {
internal.LogFailedTestInfo(t, "MiMeType", "./file.go", expected, mt1)
t.FailNow()
}
f, _ := os.Open("./file.go")
mt2 := MiMeType(f)
if mt2 != expected {
internal.LogFailedTestInfo(t, "MiMeType", "./file.go", expected, mt2)
t.FailNow()
}
}