Debian Codegraph @

example_mimetype_test.go

raw symbols SCIP
1 package mimetype_test
2
3 import (
4 "bytes"
5 "fmt"
6 "os"
7
8 "github.com/gabriel-vasile/mimetype"
9 )
10
11 func Example_detect() {
12 testBytes := []byte("This random text has a MIME type of text/plain; charset=utf-8.")
13
14 mtype := mimetype.Detect(testBytes)
15 fmt.Println(mtype.Is("text/plain"), mtype.String(), mtype.Extension())
16
17 mtype, err := mimetype.DetectReader(bytes.NewReader(testBytes))
18 fmt.Println(mtype.Is("text/plain"), mtype.String(), mtype.Extension(), err)
19
20 mtype, err = mimetype.DetectFile("a nonexistent file")
21 fmt.Println(mtype.Is("application/octet-stream"), mtype.String(), os.IsNotExist(err))
22 // Output: true text/plain; charset=utf-8 .txt
23 // true text/plain; charset=utf-8 .txt <nil>
24 // true application/octet-stream true
25 }
26
27 // Considering the definition of a binary file as "a computer file that is not
28 // a text file", they can differentiated by searching for the text/plain MIME
29 // in their MIME hierarchy.
30 func Example_textVsBinary() {
31 testBytes := []byte("This random text has a MIME type of text/plain; charset=utf-8.")
32 detectedMIME := mimetype.Detect(testBytes)
33
34 isBinary := true
35 for mtype := detectedMIME; mtype != nil; mtype = mtype.Parent() {
36 if mtype.Is("text/plain") {
37 isBinary = false
38 }
39 }
40
41 fmt.Println(isBinary, detectedMIME)
42 // Output: false text/plain; charset=utf-8
43 }
44
45 func Example_whitelist() {
46 testBytes := []byte("This random text has a MIME type of text/plain; charset=utf-8.")
47 allowed := []string{"text/plain", "application/zip", "application/pdf"}
48 mtype := mimetype.Detect(testBytes)
49
50 if mimetype.EqualsAny(mtype.String(), allowed...) {
51 fmt.Printf("%s is allowed\n", mtype)
52 } else {
53 fmt.Printf("%s is now allowed\n", mtype)
54 }
55 // Output: text/plain; charset=utf-8 is allowed
56 }
57
58 // Use Extend to add support for a file format which is not detected by mimetype.
59 //
60 // https://www.garykessler.net/library/file_sigs.html and
61 // https://github.com/file/file/tree/master/magic/Magdir
62 // have signatures for a multitude of file formats.
63 func Example_extend() {
64 foobarDetector := func(raw []byte, limit uint32) bool {
65 return bytes.HasPrefix(raw, []byte("foobar"))
66 }
67
68 mimetype.Lookup("text/plain").Extend(foobarDetector, "text/foobar", ".fb")
69 mtype := mimetype.Detect([]byte("foobar file content"))
70
71 fmt.Println(mtype.String(), mtype.Extension())
72 // Output: text/foobar .fb
73 }