How to handle MIME content types in RESTful API responses in Go?

To handle MIME content types in RESTful API responses in Go, you can use the net/http package along with the http.Header object. Here is an example on how to handle MIME content types in Go:

  1. Import the necessary packages:
import ( "net/http" )
  1. Set the appropriate content type header based on the requested MIME type:
func handler(w http.ResponseWriter, r *http.Request) { // Get the requested MIME type from the Accept header accept := r.Header.Get("Accept") // Set the appropriate content type header based on the requested MIME type switch accept { case "application/json": w.Header().Set("Content-Type", "application/json") // Handle JSON response case "application/xml": w.Header().Set("Content-Type", "application/xml") // Handle XML response case "text/html": w.Header().Set("Content-Type", "text/html") // Handle HTML response default: w.Header().Set("Content-Type", "text/plain") // Handle default response } // Write the response w.Write([]byte("Hello, World!")) }
  1. Start the HTTP server:
func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }

In the above example, the Accept header is checked to determine the requested MIME type. Based on the MIME type, the appropriate Content-Type header is set in the response. You can then handle the response based on the specified content type.

Note that this is a simplified example, and you may need to implement additional logic to handle more complex MIME content types or perform content negotiation based on the client's preference.