Blame view
locale_utility.go
1.17 KB
9933169c8 localization support |
1 2 3 4 |
package webutility import ( "encoding/json" |
a205e8f40 changes |
5 |
"errors" |
9933169c8 localization support |
6 7 |
"io/ioutil" ) |
f84e7607d added dictionary;... |
8 |
type Dictionary struct { |
a205e8f40 changes |
9 10 11 |
locales map[string]map[string]string supported []string defaultLocale string |
f84e7607d added dictionary;... |
12 13 14 15 16 17 18 |
} func NewDictionary() Dictionary { return Dictionary{ locales: map[string]map[string]string{}, } } |
9933169c8 localization support |
19 |
|
f84e7607d added dictionary;... |
20 |
func (d *Dictionary) AddLocale(loc, filePath string) error { |
9933169c8 localization support |
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
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) } |
f84e7607d added dictionary;... |
36 |
d.locales[loc] = l |
a205e8f40 changes |
37 |
d.supported = append(d.supported, loc) |
9933169c8 localization support |
38 39 40 |
return nil } |
f84e7607d added dictionary;... |
41 42 43 |
func (d *Dictionary) Translate(loc, key string) string { return d.locales[loc][key] } |
a205e8f40 changes |
44 45 46 |
func (d *Dictionary) HasLocale(loc string) bool { for _, v := range d.supported { if v == loc { |
f84e7607d added dictionary;... |
47 48 49 50 |
return true } } return false |
9933169c8 localization support |
51 |
} |
a205e8f40 changes |
52 53 54 55 56 57 58 59 60 61 62 63 |
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 } |