Grump
Grump

Reputation: 46

How to guess the type and encoding of a file given it's name in Go?

I'm looking for a quick way to guess the mime type and encoding of a file in Go, given it's name. In Python, you can do something as simple as:

import mimetypes
type, encoding = mimetypes.guess_type(file_name)

Does go have something similar? I see the mimetypes package, but I don't think it is capable of deriving the encoding from a file name.

Upvotes: 1

Views: 1832

Answers (1)

Thundercat
Thundercat

Reputation: 120979

Use mime.TypeByExtension to get the mime type given a file extension:

fmt.Println(mime.TypeByExtension(".jpg"))  // prints image/jpeg

If starting with a full file name, use filepath.Ext to get the extension and pass that extension to the function above:

fmt.Println(mime.TypeByExtension(filepath.Ext("blah.gif")))  // prints image/gif

Upvotes: 3

Related Questions