| 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 |
|
| 23 |
|
| 24 |
|
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 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 |
|
| 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 |
|
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 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 |
|
| 73 |
} |