本文整理汇总了Golang中mime.TypeByExtension函数的典型用法代码示例。如果您正苦于以下问题:Golang TypeByExtension函数的具体用法?Golang TypeByExtension怎么用?Golang TypeByExtension使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了TypeByExtension函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ContentTypesProvided
func (p *FileResource) ContentTypesProvided(req Request, cxt Context) ([]MediaTypeHandler, Request, Context, int, os.Error) {
frc := cxt.(FileResourceContext)
var arr []MediaTypeHandler
if frc.IsDir() {
arr = []MediaTypeHandler{NewJsonDirectoryListing(frc.FullPath(), req.URL().Path), NewHtmlDirectoryListing(frc.FullPath(), req.URL().Path)}
} else if frc.HasMultipleResources() {
dir, _ := path.Split(frc.FullPath())
filenames := frc.MultipleResourceNames()
arr = make([]MediaTypeHandler, len(filenames))
for i, filename := range filenames {
extension := filepath.Ext(filename)
mediaType := mime.TypeByExtension(extension)
if len(mediaType) == 0 {
// default to text/plain
mediaType = MIME_TYPE_TEXT_PLAIN
}
fullFilename := path.Join(dir, filename)
tempFrc := NewFileResourceContextWithPath(fullFilename)
arr[i] = NewPassThroughMediaTypeHandler(mediaType, tempFrc, tempFrc.Len(), tempFrc.LastModified())
}
} else {
extension := filepath.Ext(frc.FullPath())
mediaType := mime.TypeByExtension(extension)
if len(mediaType) == 0 {
// default to text/plain
mediaType = MIME_TYPE_TEXT_PLAIN
}
arr = []MediaTypeHandler{NewPassThroughMediaTypeHandler(mediaType, frc, frc.Len(), frc.LastModified())}
}
return arr, req, cxt, 0, nil
}
示例2: walkRepo
func (s *Sisho) walkRepo() error {
// * walk repo and generate constitution of repo.
err := filepath.Walk(s.tmpDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
isGitDir, isGitDirErr := regexp.MatchString(s.tmpDir+"/.git/", path)
if isGitDirErr != nil {
return err
}
if isGitDir {
return nil
}
tmp := strings.Split(path, "/")
name := tmp[len(tmp)-1]
ext := filepath.Ext(path)
r := regexp.MustCompile(s.tmpDir + "/")
if util.IsBinary(ext) {
a := ContentAsset{
Content: Content{
path: path,
relativePath: r.ReplaceAllString(path, ""),
name: name,
contentType: mime.TypeByExtension(ext),
},
ext: ext,
}
s.assets = append(s.assets, a)
return nil
}
c := Code{
Content: Content{
path: path,
relativePath: r.ReplaceAllString(path, ""),
name: name,
contentType: mime.TypeByExtension(ext),
},
Title: "",
TextLines: []string{},
}
s.contents = append(s.contents, c)
return nil
})
if err == nil {
return err
}
return nil
}
示例3: SetContentType
//设置ContentType
func (r Response) SetContentType(ext string) {
var contentType string
//判断传入的扩展名是否有.
if !strings.HasPrefix(ext, ".") {
ext = "." + ext
}
//如果能从系统mime中获取相应的type,则使用系统提供的mimetype;否则的话,将application/ext直接设置为content type
if mime.TypeByExtension(ext) != "" {
contentType = mime.TypeByExtension(ext)
} else {
contentType = "application/" + strings.TrimPrefix(ext, ".") + ";charset=utf-8"
}
r.SetHeader("Content-Type", contentType, true)
}
示例4: fileExtImpliesText
func fileExtImpliesText(ext string) (yes, unknown bool) {
defer func() {
glog.V(2).Infof("'%s' -> yes=%v unknown=%v", ext, yes, unknown)
}()
if ext == "" {
unknown = true
return
}
mt := mime.TypeByExtension(ext)
if strings.HasPrefix(mt, "text/") ||
strings.HasSuffix(mt, "+xml") ||
strings.HasSuffix(mt, ".json") ||
strings.HasSuffix(mt, "+json") {
// Most likely text.
yes = true
glog.V(1).Infof("Most likely a text extension: %s", ext)
return
}
if strings.HasPrefix(mt, "audio/") ||
strings.HasPrefix(mt, "image/") ||
strings.HasPrefix(mt, "video/") {
// Almost certainly not text.
glog.V(1).Infof("Most likely a binary extension: %s", ext)
return
}
unknown = true
return
}
示例5: load
// Slower operations to fill props struct
func (p *props) load(h hash.Hash, name string) *props {
p.mime = mime.TypeByExtension(p.ext)
r, err := os.Open(name)
if err != nil {
log.Print(name, ": Props: ", err)
return p
}
defer r.Close()
p.ftype = mapType(p.mime)
// TODO: this is quite unreadable
copy(p.chash[:], filehash(name, h, r))
copy(p.dident[:], strhash(p.dir, h))
// If the extension is empty, we need to detect
// the MIME type via file contents
if p.mime == "" {
p.mime = sniffMIME(name, r)
}
// Non-images are completely processed at this point
if !strings.HasPrefix(p.mime, "image/") {
return p
}
// Image-specific processing
if _, err := r.Seek(0, 0); err != nil {
log.Print(name, ": Seek: ", err)
return p
}
imgconf, _, err := image.DecodeConfig(r)
if err != nil {
log.Print(name, ": Image decoder: ", err)
return p
}
p.isize = image.Point{imgconf.Width, imgconf.Height}
return p
}
示例6: addFiles
func (w *messageWriter) addFiles(files []*file, isAttachment bool) {
for _, f := range files {
if _, ok := f.Header["Content-Type"]; !ok {
mediaType := mime.TypeByExtension(filepath.Ext(f.Name))
if mediaType == "" {
mediaType = "application/octet-stream"
}
f.setHeader("Content-Type", mediaType+`; name="`+f.Name+`"`)
}
if _, ok := f.Header["Content-Transfer-Encoding"]; !ok {
f.setHeader("Content-Transfer-Encoding", string(Base64))
}
if _, ok := f.Header["Content-Disposition"]; !ok {
var disp string
if isAttachment {
disp = "attachment"
} else {
disp = "inline"
}
f.setHeader("Content-Disposition", disp+`; filename="`+f.Name+`"`)
}
if !isAttachment {
if _, ok := f.Header["Content-ID"]; !ok {
f.setHeader("Content-ID", "<"+f.Name+">")
}
}
w.writeHeaders(f.Header)
w.writeBody(f.CopyFunc, Base64)
}
}
示例7: embeddedStatic
func embeddedStatic() func(http.ResponseWriter, *http.Request, *log.Logger) {
var modt = time.Now().UTC().Format(http.TimeFormat)
return func(res http.ResponseWriter, req *http.Request, log *log.Logger) {
file := req.URL.Path
if file[0] == '/' {
file = file[1:]
}
bs, ok := auto.Assets[file]
if !ok {
return
}
mtype := mime.TypeByExtension(filepath.Ext(req.URL.Path))
if len(mtype) != 0 {
res.Header().Set("Content-Type", mtype)
}
res.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs)))
res.Header().Set("Last-Modified", modt)
res.Write(bs)
}
}
示例8: newFSFile
func (h *fsHandler) newFSFile(f *os.File, fileInfo os.FileInfo, compressed bool) (*fsFile, error) {
n := fileInfo.Size()
contentLength := int(n)
if n != int64(contentLength) {
f.Close()
return nil, fmt.Errorf("too big file: %d bytes", n)
}
// detect content-type
ext := fileExtension(fileInfo.Name(), compressed)
contentType := mime.TypeByExtension(ext)
if len(contentType) == 0 {
data, err := readFileHeader(f, compressed)
if err != nil {
return nil, fmt.Errorf("cannot read header of the file %q: %s", f.Name(), err)
}
contentType = http.DetectContentType(data)
}
lastModified := fileInfo.ModTime()
ff := &fsFile{
h: h,
f: f,
contentType: contentType,
contentLength: contentLength,
compressed: compressed,
lastModified: lastModified,
lastModifiedStr: AppendHTTPDate(nil, lastModified),
t: time.Now(),
}
return ff, nil
}
示例9: MimeType
// Returns a guess at the mime type from the extension
func MimeType(o Object) string {
mimeType := mime.TypeByExtension(path.Ext(o.Remote()))
if mimeType == "" {
mimeType = "application/octet-stream"
}
return mimeType
}
示例10: ContentType
func (ctx *Context) ContentType(ext string) {
ctype := mime.TypeByExtension(ext)
if ctype != "" {
ctx.ResponseWriter.Header().Set("Content-Type", ctype)
}
}
示例11: serveCombo
// serveCombo serves the GUI JavaScript and CSS files, dynamically combined.
func (h *guiHandler) serveCombo(w http.ResponseWriter, req *http.Request) {
ctype := ""
// The combo query is like /combo/?path/to/file1&path/to/file2 ...
parts := strings.Split(req.URL.RawQuery, "&")
paths := make([]string, 0, len(parts))
for _, p := range parts {
fpath, err := getGUIComboPath(h.rootDir, p)
if err != nil {
sendError(w, errors.Annotate(err, "cannot combine files"))
return
}
if fpath == "" {
continue
}
paths = append(paths, fpath)
// Assume the Juju GUI does not mix different content types when
// combining contents.
if ctype == "" {
ctype = mime.TypeByExtension(filepath.Ext(fpath))
}
}
w.Header().Set("Content-Type", ctype)
for _, fpath := range paths {
sendGUIComboFile(w, fpath)
}
}
示例12: Deploy
// Deploys a site to S3.
func (s *Site) Deploy(user, pass, url string) error {
auth := aws.Auth{AccessKey: user, SecretKey: pass}
b := s3.New(auth, aws.USEast).Bucket(url)
// walks _site directory and uploads file to S3
walker := func(fn string, fi os.FileInfo, err error) error {
if fi.IsDir() {
return nil
}
rel, _ := filepath.Rel(s.Dest, fn)
typ := mime.TypeByExtension(filepath.Ext(rel))
content, err := ioutil.ReadFile(fn)
log.Printf(MsgUploadFile, rel)
if err != nil {
return err
}
// try to upload the file ... sometimes this fails due to amazon
// issues. If so, we'll re-try
if err := b.Put(rel, content, typ, s3.PublicRead); err != nil {
time.Sleep(100 * time.Millisecond) // sleep so that we don't immediately retry
return b.Put(rel, content, typ, s3.PublicRead)
}
// file upload was a success, return nil
return nil
}
return filepath.Walk(s.Dest, walker)
}
示例13: WriteFile
func (s *s3Provider) WriteFile(path string, content io.ReadSeeker, public bool) error {
bucket, path, err := s.getBucketPath(path)
if err != nil {
return err
}
ext := filepath.Ext(path)
mimeType := mime.TypeByExtension(ext)
if mimeType == "" {
mimeType = "application/octet-stream"
}
params := &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(path),
Body: content,
ContentType: aws.String(mimeType),
}
if public {
params.ACL = aws.String("public-read")
}
_, err = s.conn.PutObject(params)
return err
}
示例14: upload
// Copy form file to Blob
func upload(f *multipart.FileHeader) (b *blob.Blob, err error) {
// Open
upload, err := f.Open()
if err != nil {
return
}
defer upload.Close()
// Create blob
b = blob.New()
// Set filename from request
b.Name = f.Filename
// Set content-type from request
if ct := f.Header.Get("Content-Type"); ct != "" {
b.ContentType = ct
}
// Guess content-type from extension if missing
if b.ContentType == "" || b.ContentType == ApplicationOctetStream {
if ext := filepath.Ext(b.Name); ext != "" {
b.ContentType = mime.TypeByExtension(ext)
}
}
if b.ContentType == "" {
b.ContentType = ApplicationOctetStream
}
// Write
err = b.WriteFrom(upload)
if err != nil {
return
}
return
}
示例15: saveFile
//File saving routines
func saveFile(header *multipart.FileHeader, r io.Reader) (string, error) {
if client, err := storage.GetNewStorageClient(); err == nil {
h := public.NewHashString()
objName := storage.PathJoin(storage.APPLICATIONS_FOLDER_NAME, h)
//Determine the extension
var ext string = ""
if header != nil {
if segs := strings.Split(header.Filename, "."); len(segs) > 1 {
ext = "." + segs[len(segs)-1]
objName = (objName + ext)
}
}
obj := client.GetDefaultBucket().Object(objName)
objWriter := obj.NewWriter(client.Ctx)
_, err = io.Copy(objWriter, r)
objWriter.Close()
if err == nil {
if attr, e := obj.Attrs(client.Ctx); attr != nil && e == nil {
if mimeStr := mime.TypeByExtension(ext); len(mimeStr) > 0 {
attr.ContentType = mimeStr
obj.Update(client.Ctx, *attr)
}
}
return objName, nil
} else {
return "", err
}
} else {
return "", err
}
}