-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18n.go
70 lines (59 loc) · 1.48 KB
/
i18n.go
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
package just
import (
"fmt"
"sync"
)
// Translation map for one language.
type TranslationMap map[string]string
// Translator interface.
type ITranslator interface {
DefaultLocale() string
SetDefaultLocale(locale string) ITranslator
AddTranslationMap(locale string, m TranslationMap) ITranslator
Trans(locale string, message string, vars ...interface{}) string // Translate text for locale and vars.
}
type baseTranslator struct {
sync.RWMutex
defaultLocale string
localizations map[string]TranslationMap
}
func (t *baseTranslator) DefaultLocale() string {
t.Lock()
defer t.Unlock()
return t.defaultLocale
}
func (t *baseTranslator) SetDefaultLocale(locale string) ITranslator {
t.RLock()
defer t.RUnlock()
t.defaultLocale = locale
return t
}
func (t *baseTranslator) AddTranslationMap(locale string, m TranslationMap) ITranslator {
t.RLock()
defer t.RUnlock()
if t.localizations == nil {
t.localizations = make(map[string]TranslationMap)
}
if _, ok := t.localizations[locale]; !ok {
t.localizations[locale] = make(TranslationMap)
}
if m != nil {
for key, value := range m {
t.localizations[locale][key] = value
}
}
return t
}
func (t *baseTranslator) Trans(locale string, message string, vars ...interface{}) string {
if t.localizations != nil {
if m, ok := t.localizations[locale]; ok && m != nil {
if transMessage, ok := m[message]; ok {
message = transMessage
}
}
}
if len(vars) > 0 {
return fmt.Sprintf(message, vars...)
}
return message
}