github.com/jurelou/go-magic@v0.0.0-20230518182705-f2995a311800/example_package_test.go (about) 1 package magic_test 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/jurelou/go-magic" 8 ) 9 10 // This example shows how to use the Separator to split results 11 // when the "CONTINUE" flag is set and more than one match was 12 // returned by the Magic library. 13 func Example_separator() { 14 buffer := []byte("#!/bin/bash\n\n") 15 16 // Open and load the default Magic database. 17 m, err := magic.New() 18 if err != nil { 19 panic(fmt.Sprintf("An has error occurred: %s\n", err)) 20 } 21 22 m.SetFlags(magic.CONTINUE) 23 result, err := m.Buffer(buffer) 24 if err != nil { 25 panic(fmt.Sprintf("Unable to determine buffer data type: %s\n", err)) 26 } 27 28 fmt.Println("Matches for data in the buffer are:") 29 for _, s := range strings.Split(result, magic.Separator) { 30 fmt.Printf("\t%s\n", s) 31 } 32 m.Close() 33 // Should output: 34 // Matches for data in the buffer are: 35 // Bourne-Again shell script text executable 36 // a /bin/bash script, ASCII text executable 37 } 38 39 // This example shows how to use Open together with a closure. 40 func Example_closure() { 41 var s string 42 43 // When using magic.Open you don't have to worry 44 // about closing the the Magic database. 45 err := magic.Open(func(m *magic.Magic) error { 46 m.SetFlags(magic.MIME) 47 mime, err := m.File("test/fixtures/gopher.png") 48 if err != nil { 49 return err // Propagate error outside of the closure. 50 } 51 s = mime // Pass results outside. 52 return nil 53 }) 54 if err != nil { 55 panic(fmt.Sprintf("An has error occurred: %s\n", err)) 56 } 57 fmt.Printf("File MIME type is: %s\n", s) 58 // Output: 59 // File MIME type is: image/png; charset=binary 60 } 61 62 // func Example_disable_autoload() { 63 // } 64 65 // func Example_do_not_stop_on_errors() { 66 // }