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:
import (
"net/http"
)
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!"))
}
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.