go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/web/detect_content_type.go (about)

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