Go语言学习之mime包(the way to go)
生命不止,继续 go go go !!! 很久之前,写过一篇文章来介绍Windows下如何获取文件的MIME: 其中,用到了叫做名为FindMimeFromData的Windows api. 所以今天介绍一下golang中为我们提供的mime package。 MIMEMIME是英文Multipurpose Internet Mail Extensions的缩写: MIME is an Internet standard that extends the format of email to support: Package mimefunc AddExtensionType func AddExtensionType(ext,typ string) error
AddExtensionType sets the MIME type associated with the extension ext to typ. The extension should begin with a leading dot,as in “.html”. mime.AddExtensionType(".svg","image/svg+xml")
mime.AddExtensionType( ".m3u8","application/x-mpegURL" );
mime.AddExtensionType( ".ts","video/MP2T" );
func FormatMediaType func FormatMediaType(t string,param map[string]string) string
FormatMediaType serializes mediatype t and the parameters param as a media type conforming to RFC 2045 and RFC 2616. The type and parameter names are written in lower-case. When any of the arguments result in a standard violation then FormatMediaType returns the empty string. s := mime.FormatMediaType("image/svg+xml",map[string]string{"svg": "u0001"})
fmt.Printf("%#v",s)
func ParseMediaType func ParseMediaType(v string) (mediatype string,params map[string]string,err error)
ParseMediaType parses a media type value and any optional parameters,per RFC 1521. Media types are the values in Content-Type and Content-Disposition headers (RFC 2183). On success,ParseMediaType returns the media type converted to lowercase and trimmed of white space and a non-nil map. The returned map,params,maps from the lowercase attribute to the attribute value with its case preserved. package main
import (
"fmt"
"mime"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage : %s filename n",os.Args[0])
os.Exit(1)
}
mType,parameters,err := mime.ParseMediaType(os.Args[1])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Media type : ",mType)
for param := range parameters {
fmt.Printf("%v = %vnn",param,parameters[param])
}
}
func TypeByExtension func TypeByExtension(ext string) string
TypeByExtension returns the MIME type associated with the file extension ext. The extension ext should begin with a leading dot,as in “.html”. When ext has no associated type,TypeByExtension returns “”. MIME应用获取文件的mime: package main
import (
"fmt"
"mime"
"path"
)
func main() {
filepath := "./1.png"
mimetype := mime.TypeByExtension(path.Ext(filepath))
fmt.Println(mimetype)
filepath = "./2.txt"
mimetype = mime.TypeByExtension(path.Ext(filepath))
fmt.Println(mimetype)
filepath = "./3.html"
mimetype = mime.TypeByExtension(path.Ext(filepath))
fmt.Println(mimetype)
}
输出: 设置Content-Type func SetContentTypeFromExtension(w http.ResponseWriter,extension string) {
mime := mime.TypeByExtension(extension)
if mime != "" {
w.Header().Set("Content-Type",mime)
}
}
解析Content-Type mediatype,err := mime.ParseMediaType(contentType)
fmt.Printf("mediatype=%v,params=%v %v,err=%vn",mediatype,len(params),err)
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |