How to implement custom MIME type handling for specific file extensions in Go?

To implement custom MIME type handling for specific file extensions in Go, you can follow these steps:

  1. Import the mime and net/http packages in your Go file.
import ( "mime" "net/http" )
  1. Register your custom MIME types and file extensions using the mime.AddExtensionType function. Define the MIME type you want to associate with the file extension.
func init() { mime.AddExtensionType(".custom", "application/x-custom") }
  1. Create an HTTP handler function that serves files with the custom extension. In the handler, set the Content-Type header to the desired MIME type.
func serveCustomFile(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/x-custom") http.ServeFile(w, r, "path/to/file.custom") // Replace with the actual file path }
  1. Define a custom HTTP server using the http.ServeMux or http.Handle function.
func main() { mux := http.NewServeMux() mux.HandleFunc("/custom", serveCustomFile) http.ListenAndServe(":8080", mux) }
  1. Run the program, and the custom file with the specific extension will be served with the defined MIME type when accessed through the /custom URL.

Make sure to replace "path/to/file.custom" with the actual file path you want to serve. Additionally, you can modify the MIME type and the extension according to your requirements.