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