How to implement MIME content negotiation for serving different content types based on client preferences in Go?

To implement MIME content negotiation for serving different content types based on client preferences in Go, you can follow these steps:

  1. Import the necessary packages:
import ( "net/http" "strings" )
  1. Create a function to handle the negotiation logic:
func negotiateContent(r *http.Request, supportedTypes []string) string { // Get the Accept header from the request acceptHeader := r.Header.Get("Accept") // Split the Accept header into individual media types acceptTypes := strings.Split(acceptHeader, ",") // Select the first supported media type for _, acceptType := range acceptTypes { for _, supportedType := range supportedTypes { if acceptType == supportedType { return supportedType } } } // If no match is found, return a default type return "application/octet-stream" }
  1. Use the negotiation logic in your HTTP handler:
func MyHandler(w http.ResponseWriter, r *http.Request) { // Define the supported content types supportedTypes := []string{ "text/plain", "application/json", "application/xml", } // Perform content negotiation contentType := negotiateContent(r, supportedTypes) // Set the Content-Type header based on the negotiated type w.Header().Set("Content-Type", contentType) // Write the response body switch contentType { case "text/plain": w.Write([]byte("This is a plain text response")) case "application/json": w.Write([]byte("{\"message\": \"This is a JSON response\"}")) case "application/xml": w.Write([]byte("<message>This is an XML response</message>")) default: // Handle the default case } }
  1. Register your handler and start the HTTP server:
func main() { http.HandleFunc("/", MyHandler) http.ListenAndServe(":8080", nil) }

Now, when a client sends a request to your server, the negotiation logic will select the appropriate content type based on the client's preferences and the supported types. The server will then respond with the corresponding content.