diff options
author | clsr <clsr@clsr.net> | 2017-08-18 13:47:07 +0200 |
---|---|---|
committer | clsr <clsr@clsr.net> | 2017-08-18 13:47:07 +0200 |
commit | 91469fdebf57ff683cc2a7d9373cdee554ed3aba (patch) | |
tree | 1944f2a2e450127f2404b0bef4bf75c8169a8bc5 /magic.go | |
download | cn-fileserver-0.1.0.tar.gz cn-fileserver-0.1.0.zip |
Initial commitv0.1.0
Diffstat (limited to 'magic.go')
-rw-r--r-- | magic.go | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/magic.go b/magic.go new file mode 100644 index 0000000..a6fb48d --- /dev/null +++ b/magic.go @@ -0,0 +1,32 @@ +package main + +// #cgo LDFLAGS: -lmagic +// #include <stdlib.h> +// #include <magic.h> +import "C" +import "errors" +import "unsafe" + +var magic C.magic_t + +func init() { + magic = C.magic_open(C.MAGIC_MIME_TYPE | C.MAGIC_SYMLINK | C.MAGIC_ERROR) + if magic == nil { + panic("unable to initialize libmagic") + } + if C.magic_load(magic, nil) != 0 { + C.magic_close(magic) + panic("unable to load libmagic database: " + C.GoString(C.magic_error(magic))) + } +} + +// GetMimeType uses libmagic to find the mime type of a file by filename. +func GetMimeType(fname string) (string, error) { + cfname := C.CString(fname) + defer C.free(unsafe.Pointer(cfname)) + mime := C.magic_file(magic, cfname) + if mime == nil { + return "", errors.New(C.GoString(C.magic_error(magic))) + } + return C.GoString(mime), nil +} |