github.com/jurelou/go-magic@v0.0.0-20230518182705-f2995a311800/example_test.go (about)

     1  package magic_test
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/jurelou/go-magic"
     7  )
     8  
     9  // This example show the basic usage of the package: Open and initialize
    10  // the Magic library, set appropriate flags, for a given file find its
    11  // MIME identification (as per the flag set), print the results and close
    12  // releasing all initialized resources.
    13  func Example_basic() {
    14  	// Open and load the default Magic database.
    15  	m, err := magic.New()
    16  	if err != nil {
    17  		panic(fmt.Sprintf("An has error occurred: %s\n", err))
    18  	}
    19  
    20  	m.SetFlags(magic.MIME)
    21  	mime, err := m.File("test/fixtures/gopher.png")
    22  	if err != nil {
    23  		panic(fmt.Sprintf("Unable to determine file MIME: %s\n", err))
    24  	}
    25  	fmt.Printf("File MIME is: %s\n", mime)
    26  
    27  	m.Close()
    28  	// Output:
    29  	// File MIME is: image/png; charset=binary
    30  }
    31  
    32  // func Example_must() {
    33  // }
    34  
    35  // This example shows how to quickly find MIME type for a file.
    36  func ExampleFileType() {
    37  	// The magic.FileType function will open the Magic database,
    38  	// set flags to "MIME", return the result, and then close
    39  	// the Magic database afterwards.
    40  	mime, err := magic.FileType("test/fixtures/gopher.png")
    41  	if err != nil {
    42  		panic(fmt.Sprintf("An has error occurred: %s\n", err))
    43  	}
    44  	fmt.Printf("File MIME type is: %s\n", mime)
    45  	// Output:
    46  	// File MIME type is: image/png
    47  }
    48  
    49  // This example show how to identify encoding type of a buffer.
    50  func ExampleBufferEncoding() {
    51  	buffer := []byte("Hello, 世界")
    52  
    53  	mime, err := magic.BufferEncoding(buffer)
    54  	if err != nil {
    55  		panic(fmt.Sprintf("An has error occurred: %s\n", err))
    56  	}
    57  	fmt.Printf("Data in the buffer is encoded as: %s\n", mime)
    58  	// Output:
    59  	// Data in the buffer is encoded as: utf-8
    60  }