summaryrefslogtreecommitdiffstats
path: root/magic.go
blob: a6fb48d73e4daebfde78bb382534627abce63d65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
}