numerus/pkg/locale.go

95 lines
2.0 KiB
Go

package pkg
import (
"context"
"net/http"
"github.com/leonelquinteros/gotext"
"golang.org/x/text/language"
)
const contextLocaleKey = "numerus-locale"
type Locale struct {
*gotext.Locale
Language language.Tag
}
func NewLocale(lang language.Tag) *Locale {
return &Locale{
gotext.NewLocale("locales", lang.String()),
lang,
}
}
func SetLocale(db *Db, next http.Handler) http.Handler {
availableLanguages := mustGetAvailableLanguages(db)
var matcher = language.NewMatcher(availableLanguages)
locales := map[language.Tag]*Locale{}
for _, lang := range availableLanguages {
locale := NewLocale(lang)
locale.AddDomain("numerus")
locales[lang] = locale
}
defaultLocale := locales[language.Catalan]
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var locale *Locale
user := getUser(r)
locale = locales[user.Language]
if locale == nil {
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) *Locale {
return r.Context().Value(contextLocaleKey).(*Locale)
}
func pgettext(context string, str string, locale *Locale) string {
return locale.GetC(str, context)
}
func gettext(str string, locale *Locale) string {
return locale.Get(str)
}
func mustGetAvailableLanguages(db *Db) []language.Tag {
rows, err := db.Query(context.Background(), "select lang_tag from language where selectable")
if err != nil {
panic(err)
}
defer rows.Close()
var langs []language.Tag
for rows.Next() {
var langTag string
err = rows.Scan(&langTag)
if err != nil {
panic(err)
}
langs = append(langs, language.MustParse(langTag))
}
if rows.Err() != nil {
panic(rows.Err())
}
return langs
}