To implement MIME-based content type negotiation for language preferences in Go, you can use the net/http
package along with the acceptlanguage
library.
Here's an example:
acceptlanguage
library:go get github.com/sykora-ondrej/go-accept-language
import (
"net/http"
"strings"
"github.com/sykora-ondrej/go-accept-language"
)
func myHandler(w http.ResponseWriter, r *http.Request) {
// Get the "Accept-Language" header from the request
acceptLanguageHeader := r.Header.Get("Accept-Language")
// Parse the "Accept-Language" header using the acceptlanguage library
al := acceptlanguage.Parse(acceptLanguageHeader)
// Get the user's preferred language from the parsed header
preferredLanguage := al.Languages[0]
// Perform content negotiation based on the preferred language
if strings.HasPrefix(preferredLanguage.Code, "en") {
// Return English content
w.Write([]byte("Hello, world!"))
} else if strings.HasPrefix(preferredLanguage.Code, "fr") {
// Return French content
w.Write([]byte("Bonjour, le monde !"))
} else {
// Return a default language content
w.Write([]byte("Hello, world!"))
}
}
func main() {
http.HandleFunc("/", myHandler)
http.ListenAndServe(":8080", nil)
}
In the example above, when a client sends a request, the server extracts the "Accept-Language" header from the request and uses the acceptlanguage
library to parse it. It then performs content negotiation based on the preferred language and returns the corresponding content.
Note: Make sure to handle any potential errors related to parsing the "Accept-Language" header or performing content negotiation to ensure the correct behavior of your code.