Go语言学习之mime包(the way to go)

前端之家收集整理的这篇文章主要介绍了Go语言学习之mime包(the way to go)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

生命不止,继续 go go go !!!

很久之前,写过一篇文章来介绍Windows下如何获取文件的MIME:
windows客户端开发–获取windows系统中文件的MIME

其中,用到了叫做名为FindMimeFromData的Windows api.

所以今天介绍一下golang中为我们提供的mime package。

MIME

MIME是英文Multipurpose Internet Mail Extensions的缩写:

MIME is an Internet standard that extends the format of email to support:
Text in character sets other than ASCII
Non-text attachments: audio,video,images,application programs etc.
Message bodies with multiple parts
Header information in non-ASCII character sets

Package mime

func 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”.
函数将扩展名和mimetype建立偶联;扩展名应以点号开始,例如”.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.
函数根据RFC 2045和 RFC 2616的规定将媒体类型t和参数param连接为一个mime媒体类型,类型和参数都采用小写字母。任一个参数不合法都会返回空字符串。

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.
函数根据RFC 1521解析一个媒体类型值以及可能的参数。媒体类型值一般应为Content-Type和Conten-Disposition头域的值(参见RFC 2183)。成功的调用会返回小写字母、去空格的媒体类型和一个非空的map。返回的map映射小写字母的属性和对应的属性值。

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 = %v\n\n",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类型。扩展名应以点号开始,如”.html”。如果扩展名未偶联类型,函数会返回”“。
内建的偶联表很小,但在unix系统会从本地系统的一或多个mime.types文件(参加下表)进行增补。

MIME应用

获取文件的mime:
这里使用的path包的Ext方法获取路径字符串中的文件扩展名。

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)
}

输出
image/png
text/plain; charset=utf-8
text/html; charset=utf-8

设置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=%v\n",mediatype,len(params),err)

猜你在找的Go相关文章