numerus/pkg/locale.go

51 lines
1.2 KiB
Go

package pkg
import (
"context"
"net/http"
"github.com/leonelquinteros/gotext"
"golang.org/x/text/language"
)
const contextLocaleKey = "numerus-locale"
func Locale(next http.Handler) http.Handler {
supportedLanguages := []language.Tag{
language.Catalan,
language.Spanish,
}
var matcher = language.NewMatcher(supportedLanguages)
locales := map[language.Tag]*gotext.Locale{}
for _, lang := range supportedLanguages {
locale := gotext.NewLocale("locales", lang.String())
locale.AddDomain("numerus")
locales[lang] = locale
}
defaultLocale := locales[language.Catalan]
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var locale *gotext.Locale
t, _, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
if err == nil {
tag, _, _ := matcher.Match(t...)
var ok bool
locale, ok = locales[tag]
for !ok && !tag.IsRoot() {
tag = tag.Parent()
locale, ok = locales[tag]
}
}
if locale == nil {
locale = defaultLocale
}
ctx := context.WithValue(r.Context(), contextLocaleKey, locale)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func getLocale(r *http.Request) *gotext.Locale {
return r.Context().Value(contextLocaleKey).(*gotext.Locale)
}