localization.go
1.17 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
package webutility
import (
"encoding/json"
"errors"
"io/ioutil"
)
type Dictionary struct {
locales map[string]map[string]string
supported []string
defaultLocale string
}
func NewDictionary() Dictionary {
return Dictionary{
locales: map[string]map[string]string{},
}
}
func (d *Dictionary) AddLocale(loc, filePath string) error {
file, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
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)
}
d.locales[loc] = l
d.supported = append(d.supported, loc)
return nil
}
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
}