i18ner.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package i18n
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "github.com/nicksnyder/go-i18n/v2/i18n"
  7. "golang.org/x/text/language"
  8. "golang.org/x/text/message"
  9. "gopkg.in/yaml.v2"
  10. )
  11. var Bundle = &i18n.Bundle{
  12. DefaultLanguage: language.English,
  13. UnmarshalFuncs: map[string]i18n.UnmarshalFunc{
  14. "yaml": yaml.Unmarshal,
  15. },
  16. }
  17. /*
  18. WithPrinter() is a higher-order function injecting into the request context a
  19. printer for the language best matching the Accept-Language header in the incoming
  20. request.
  21. The wrapped handler can use Printer() to get a message printer instance
  22. configured for the best available language for the request.
  23. */
  24. func WithPrinter(h http.Handler) http.Handler {
  25. h2 := func(w http.ResponseWriter, r *http.Request) {
  26. localizer := i18n.NewLocalizer(Bundle, r.Header.Get("Accept-Language"))
  27. c := context.WithValue(r.Context(), "localizer", &localizer)
  28. h.ServeHTTP(w, r.WithContext(c))
  29. }
  30. return http.HandlerFunc(h2)
  31. }
  32. /*
  33. Printer() returns a message printer configured for the language best matching the
  34. Accept-Language in the request, or panic if the handler invoking it was not
  35. wrapped by a WithPrinter() call.
  36. */
  37. func Printer(r *http.Request) *message.Printer {
  38. p, ok := r.Context().Value("printer").(*message.Printer)
  39. if !ok {
  40. panic(errors.New("trying to use i18n.Printer in a handler not wrapped with i18.WithPrinter"))
  41. }
  42. return p
  43. }