-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
64 lines (52 loc) · 1.33 KB
/
main.go
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Program detects the mimetype of a file using a lib written in go which does the detection without using external libs.
// Detection is done by what are called magic numbers.
// These magic numbers are defined in the first bytes of the file.
// At the link https://www.garykessler.net/library/file_sigs.html we have documentation on several of these magic bytes
//
// Example for PDF detection
// on the link above do the search: 25 50 44 46
//
// in the code the implementation looked like this:
//
// func Pdf(in []byte) bool {
// return len(in) > 4 && bytes.Equal(in[:4], []byte{0x25, 0x50, 0x44, 0x46})
// }
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/gabriel-vasile/mimetype"
"strings"
)
type ok struct {
Mime string `json:"mime"`
Extension string `json:"extension"`
}
type fail struct {
Error string `json:"error"`
}
func printJson(result interface{}) {
j, err := json.Marshal(result)
if err != nil {
panic("json error")
}
fmt.Print(string(j))
}
func main() {
var file string
flag.StringVar(&file, "file", "", "type filename")
flag.Parse()
if strings.TrimSpace(file) == "" {
flag.Usage()
return
}
mime, err := mimetype.DetectFile(file)
if err != nil {
r := fail{Error: err.Error()}
printJson(r)
return
}
r := ok{Mime: mime.String(), Extension: mime.Extension()}
printJson(r)
}