1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- package i18n
- import (
- "context"
- "errors"
- "net/http"
- "github.com/nicksnyder/go-i18n/v2/i18n"
- "golang.org/x/text/language"
- "golang.org/x/text/message"
- "gopkg.in/yaml.v2"
- )
- var Bundle = &i18n.Bundle{
- DefaultLanguage: language.English,
- UnmarshalFuncs: map[string]i18n.UnmarshalFunc{
- "yaml": yaml.Unmarshal,
- },
- }
- /*
- 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) {
- localizer := i18n.NewLocalizer(Bundle, r.Header.Get("Accept-Language"))
- c := context.WithValue(r.Context(), "localizer", &localizer)
- 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
- }
|