i18ner.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package i18n
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "golang.org/x/text/message"
  7. )
  8. /*
  9. WithPrinter() is a higher-order function injecting into the request context a
  10. printer for the language best matching the Accept-Language header in the incoming
  11. request.
  12. The wrapped handler can use Printer() to get a message printer instance
  13. configured for the best available language for the request.
  14. */
  15. func WithPrinter(h http.Handler) http.Handler {
  16. h2 := func(w http.ResponseWriter, r *http.Request) {
  17. // Utilise le matcher de message.DefaultCatalog.
  18. tag := message.MatchLanguage(r.Header.Get("Accept-Language"))
  19. c := context.WithValue(r.Context(), "printer", message.NewPrinter(tag))
  20. h.ServeHTTP(w, r.WithContext(c))
  21. }
  22. return http.HandlerFunc(h2)
  23. }
  24. /*
  25. Printer() returns a message printer configured for the language best matching the
  26. Accept-Language in the request, or panic if the handler invoking it was not
  27. wrapped by a WithPrinter() call.
  28. */
  29. func Printer(r *http.Request) *message.Printer {
  30. p, ok := r.Context().Value("printer").(*message.Printer)
  31. if !ok {
  32. panic(errors.New("trying to use i18n.Printer in a handler not wrapped with i18.WithPrinter"))
  33. }
  34. return p
  35. }