Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Decoder constructor with magic database file #27

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion magicmime.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

// +build linux darwin
// +build linux darwin windows

// Package magicmime detects mimetypes using libmagic.
// This package requires libmagic, install it by the following
Expand Down Expand Up @@ -143,6 +143,31 @@ func NewDecoder(flags Flag) (*Decoder, error) {
return d, nil
}

// NewDecoderWithMagicDB creates a detector with the magic database file and the specified flags. Upon
// success users are expected to call Close on the returned Decoder
// when it is no longer needed.
func NewDecoderWithMagicDB(flags Flag, magicDB string) (*Decoder, error) {
db := C.magic_open(C.int(0))
if db == nil {
return nil, errors.New("error opening magic")
}
d := &Decoder{db: db}
var err error
if code := C.magic_setflags(db, C.int(flags)); code != 0 {
err = errors.New(C.GoString(C.magic_error(d.db)))
d.Close()
return nil, err
}
path := C.CString(magicDB)
defer C.free(unsafe.Pointer(path))
if code := C.magic_load(db, path); code != 0 {
err = errors.New(C.GoString(C.magic_error(d.db)))
d.Close()
return nil, err
}
return d, nil
}

// TypeByFile looks up for a file's mimetype by its content.
// It uses a magic number database which is described in magic(5).
func (d *Decoder) TypeByFile(filename string) (string, error) {
Expand Down