magic

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2025 License: GPL-2.0 Imports: 8 Imported by: 10

README

magic

Toolkit for detecting and verifying file type using magic bytes in pure Go.

Support for all file signatures supported by FreeDesktop (and a few more.)

A MIME type, description, and a suggested file extension and icon name are provided for each lookup.

A binary is also included for ease of use.

Binary Usage

$ go install github.com/liamg/magic/cmd/latest@latest
$ magic /path/to/file

Module Usage

See the docs for full details.

package main

import (
	"fmt"
	"os"

	"github.com/liamg/magic"
)

func main() {
	ft, err := magic.IdentifyPath(os.Args[1])
	if err != nil {
		fmt.Printf("\x1b[31mError identifying file: %s\x1b[0m\n", err)
		os.Exit(1)
	}

	fmt.Printf("File         %s\n", os.Args[1])
	fmt.Printf("Description  %s\n", ft.Description)
	fmt.Printf("MIME         %s\n", ft.MIME)
	fmt.Printf("Icon         %s\n", ft.Icon)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DataMatcher added in v1.0.0

type DataMatcher struct {
	Submatches []DataSubMatcher
	Result     FileType
	Priority   int
}

func (*DataMatcher) MatchBytes added in v1.0.0

func (m *DataMatcher) MatchBytes(b *bufferedReader) bool

type DataSubMatcher added in v1.0.0

type DataSubMatcher struct {
	Bytes    []byte
	Offsets  []int
	Mask     []byte
	Children []DataSubMatcher
}

func (*DataSubMatcher) Match added in v1.0.0

func (m *DataSubMatcher) Match(data []byte) bool

type FileType

type FileType struct {
	Description          string
	RecommendedExtension string
	Icon                 string
	MIME                 string
}

FileType provides information about the type of the file inferred from the provided magic bytes

func Identify added in v1.0.0

func Identify(r io.Reader) FileType

Identify looks up the file type based on the provided bytes.

func IdentifyPath added in v1.0.0

func IdentifyPath(path string) (FileType, error)

func IdentifyWithFilename added in v1.0.0

func IdentifyWithFilename(r io.Reader, filename string) FileType

IdentifyWithFilename looks up the file type based on the provided filename, falling back to the bytes if needed. See https://specifications.freedesktop.org/shared-mime-info/latest/ar01s02.html#id-1.3.15 for checking order

type FilenameMatcher added in v1.0.0

type FilenameMatcher struct {
	Pattern  string
	Result   FileType
	Priority int
}

Directories

Path Synopsis
cmd
generator command
magic command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL