package i18n import ( "context" "errors" "net/http" "golang.org/x/text/message" ) /* WithPrinter() is a higher-order function injecting into the request context a printer for the language best matching the Accept-Language header in the incoming request. The wrapped handler can use Printer() to get a message printer instance configured for the best available language for the request. */ func WithPrinter(h http.Handler) http.Handler { h2 := func(w http.ResponseWriter, r *http.Request) { // Utilise le matcher de message.DefaultCatalog. tag := message.MatchLanguage(r.Header.Get("Accept-Language")) c := context.WithValue(r.Context(), "printer", message.NewPrinter(tag)) h.ServeHTTP(w, r.WithContext(c)) } return http.HandlerFunc(h2) } /* Printer() returns a message printer configured for the language best matching the Accept-Language in the request, or panic if the handler invoking it was not wrapped by a WithPrinter() call. */ func Printer(r *http.Request) *message.Printer { p, ok := r.Context().Value("printer").(*message.Printer) if !ok { panic(errors.New("trying to use i18n.Printer in a handler not wrapped with i18.WithPrinter")) } return p }