1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
package utils
import (
"io/ioutil"
"net/http"
"path/filepath"
"strings"
l4g "github.com/alecthomas/log4go"
"github.com/cloudfoundry/jibber_jabber"
"github.com/mattermost/platform/model"
"github.com/nicksnyder/go-i18n/i18n"
)
var T i18n.TranslateFunc
var locales map[string]string = make(map[string]string)
func InitTranslations() {
i18nDirectory := FindDir("i18n")
files, _ := ioutil.ReadDir(i18nDirectory)
for _, f := range files {
if filepath.Ext(f.Name()) == ".json" {
filename := f.Name()
locales[strings.Split(filename, ".")[0]] = i18nDirectory + filename
i18n.MustLoadTranslationFile(i18nDirectory + filename)
}
}
T = GetTranslationsBySystemLocale()
}
func GetTranslationsBySystemLocale() i18n.TranslateFunc {
locale := model.DEFAULT_LOCALE
if userLanguage, err := jibber_jabber.DetectLanguage(); err == nil {
if _, ok := locales[userLanguage]; ok {
locale = userLanguage
} else {
l4g.Error("Failed to load system translations for '%v' attempting to fall back to '%v'", locale, model.DEFAULT_LOCALE)
locale = model.DEFAULT_LOCALE
}
}
if locales[locale] == "" {
panic("Failed to load system translations for '" + model.DEFAULT_LOCALE + "'")
}
translations := TfuncWithFallback(locale)
if translations == nil {
panic("Failed to load system translations")
}
l4g.Info(translations("utils.i18n.loaded"), locale, locales[locale])
return translations
}
func GetUserTranslations(locale string) i18n.TranslateFunc {
if _, ok := locales[locale]; !ok {
locale = model.DEFAULT_LOCALE
}
translations := TfuncWithFallback(locale)
return translations
}
func SetTranslations(locale string) i18n.TranslateFunc {
translations := TfuncWithFallback(locale)
return translations
}
func GetTranslationsAndLocale(w http.ResponseWriter, r *http.Request) (i18n.TranslateFunc, string) {
headerLocale := strings.Split(strings.Split(r.Header.Get("Accept-Language"), ",")[0], "-")[0]
if locales[headerLocale] != "" {
translations := TfuncWithFallback(headerLocale)
return translations, headerLocale
}
translations := TfuncWithFallback(model.DEFAULT_LOCALE)
return translations, model.DEFAULT_LOCALE
}
func TfuncWithFallback(pref string) i18n.TranslateFunc {
t, _ := i18n.Tfunc(pref)
return func(translationID string, args ...interface{}) string {
if translated := t(translationID, args...); translated != translationID {
return translated
}
t, _ := i18n.Tfunc("en")
return t(translationID, args...)
}
}
|