github.com/blend/go-sdk@v1.20220411.3/webutil/detect_content_type.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package webutil 9 10 import ( 11 "net/http" 12 "os" 13 "path/filepath" 14 15 "github.com/blend/go-sdk/ex" 16 ) 17 18 // KnownExtenions are known extenions mapped to their content types. 19 var ( 20 KnownExtensions = map[string]string{ 21 ".html": "text/html; charset=utf-8", 22 ".xml": "text/xml; charset", 23 ".json": "application/json; charset=utf-8", 24 ".css": "text/css; charset=utf-8", 25 ".js": "application/javascript", 26 ".jpg": "image/jpeg", 27 ".jpeg": "image/jpeg", 28 ".png": "image/png", 29 } 30 ) 31 32 // DetectContentType generates the content type of a given file by path. 33 func DetectContentType(path string) (string, error) { 34 if contentType, ok := KnownExtensions[filepath.Ext(path)]; ok { 35 return contentType, nil 36 } 37 38 f, err := os.Open(path) 39 if err != nil { 40 return "", ex.New(err) 41 } 42 defer f.Close() 43 header := make([]byte, 512) 44 _, err = f.Read(header) 45 if err != nil { 46 return "", ex.New(err) 47 } 48 return http.DetectContentType(header), nil 49 }