How to handle MIME content type mapping and conversion in Go web applications?

In Go web applications, you can handle MIME content type mapping and conversion using the net/http package. Here's how you can do it:

  1. Define a mapping of file extensions to MIME types in your application. You can use a simple map for this:
var mimeTypes = map[string]string{ ".html": "text/html", ".css": "text/css", ".js": "application/javascript", ".png": "image/png", // add more mappings as needed }
  1. Create a http.FileServer handler to serve static files from a directory:
fileServer := http.FileServer(http.Dir("path/to/static/files"))
  1. Wrap the file server handler with a new handler that performs the MIME type lookup and sets the Content-Type header accordingly:
http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Get the file path from the URL filePath := string(r.URL.Path[1:]) // Lookup the MIME type based on the file extension mimeType := mimeTypes[path.Ext(filePath)] // Set the Content-Type header w.Header().Set("Content-Type", mimeType) // Serve the static file using the file server handler fileServer.ServeHTTP(w, r) }))
  1. Start your web server:
http.ListenAndServe(":8080", nil)

With this setup, your web application will serve static files with the appropriate Content-Type header based on their file extensions. You can extend the mimeTypes map with additional mappings as needed for your application's specific file types.