numerus/pkg/locale.go

71 lines
1.6 KiB
Go

package pkg
import (
"context"
"net/http"
"github.com/leonelquinteros/gotext"
"golang.org/x/text/language"
)
const contextLocaleKey = "numerus-locale"
func Locale(db *Db, next http.Handler) http.Handler {
availableLanguages := getAvailableLanguages(db)
var matcher = language.NewMatcher(availableLanguages)
locales := map[language.Tag]*gotext.Locale{}
for _, lang := range availableLanguages {
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)
}
func getAvailableLanguages(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 lang_tag string
err = rows.Scan(&lang_tag)
if err != nil {
panic(err)
}
langs = append(langs, language.MustParse(lang_tag))
}
if rows.Err() != nil {
panic(rows.Err())
}
return langs
}