localization.go
2.08 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package webutility
import (
"encoding/json"
"errors"
"io/ioutil"
"path"
"strings"
"sync"
)
type Dictionary struct {
my sync.Mutex
locales map[string]map[string]string
supported []string
defaultLocale string
}
func NewDictionary() *Dictionary {
return &Dictionary{
locales: map[string]map[string]string{},
}
}
func (d *Dictionary) AddTranslations(directory string) error {
files, err := ioutil.ReadDir(directory)
if err != nil {
return err
}
for _, fileInfo := range files {
fName := fileInfo.Name()
path := directory + "/" + fName
file, err := ioutil.ReadFile(path)
if err != nil {
return err
}
loc := stripFileExtension(fName)
var data interface{}
err = json.Unmarshal(file, &data)
if err != nil {
return err
}
l := map[string]string{}
for k, v := range data.(map[string]interface{}) {
l[k] = v.(string)
}
mu.Lock()
defer mu.Unlock()
d.locales[loc] = l
d.supported = append(d.supported, loc)
}
return nil
}
func (d *Dictionary) GetBestMatchLocale(acceptedLanguages string) (best string) {
accepted := d.parseAcceptedLanguageHeader(acceptedLanguages)
best = accepted[0]
return
}
func (d *Dictionary) Translate(loc, key string) string {
return d.locales[loc][key]
}
func (d *Dictionary) hasLocale(loc string) bool {
for _, v := range d.supported {
if v == loc {
return true
}
}
return false
}
func (d *Dictionary) setDefaultLocale(loc string) error {
if !d.hasLocale(loc) {
return errors.New("dictionary does not contain translations for " + loc)
}
d.defaultLocale = loc
return nil
}
func (d *Dictionary) getDefaultLocale() string {
return d.defaultLocale
}
func (d *Dictionary) parseAcceptedLanguageHeader(acceptedLanguages string) (langs []string) {
if acceptedLanguages == "" {
langs = append(langs, d.getDefaultLocale())
return
}
parts := strings.Split(acceptedLanguages, ",")
for _, p := range parts {
langs = append(langs, p)
}
return
}
func stripFileExtension(full string) (stripped string) {
extension := path.Ext(full)
stripped = strings.TrimSuffix(full, extension)
return stripped
}