package i18n import ( "context" "errors" "log" "net/http" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" "gopkg.in/yaml.v2" ) var Bundle = &i18n.Bundle{ DefaultLanguage: language.English, UnmarshalFuncs: map[string]i18n.UnmarshalFunc{ "yaml": yaml.Unmarshal, }, } const localizerKey = "localizer" /* WithLocalizer() 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 Localizer() to get a message printer instance configured for the best available language for the request. */ func WithLocalizer(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(), localizerKey, localizer) h.ServeHTTP(w, r.WithContext(c)) } return http.HandlerFunc(h2) } /* Localizer() 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 WithLocalizer() call. */ func Localizer(r *http.Request) *i18n.Localizer { ip := r.Context().Value(localizerKey) p, ok := ip.(*i18n.Localizer) if !ok { log.Println(errors.New("trying to use i18n.Localizer in a handler not wrapped with i18.WithLocalizer")) // In that case, p will be nil, which is a valid localizer doing no localization. } return p }