Blame view
localization.go
1.71 KB
9933169c8 localization support |
1 2 3 4 |
package webutility import ( "encoding/json" |
a205e8f40 changes |
5 |
"errors" |
9933169c8 localization support |
6 |
"io/ioutil" |
3712c373f better localizati... |
7 |
"strings" |
3fffcb954 removed old http API |
8 |
"sync" |
9933169c8 localization support |
9 |
) |
f84e7607d added dictionary;... |
10 |
type Dictionary struct { |
3fffcb954 removed old http API |
11 |
my sync.Mutex |
a205e8f40 changes |
12 13 14 |
locales map[string]map[string]string supported []string defaultLocale string |
f84e7607d added dictionary;... |
15 |
} |
ad8e9dd2a added middleware ... |
16 17 |
func NewDictionary() *Dictionary { return &Dictionary{ |
f84e7607d added dictionary;... |
18 19 20 |
locales: map[string]map[string]string{}, } } |
9933169c8 localization support |
21 |
|
f84e7607d added dictionary;... |
22 |
func (d *Dictionary) AddLocale(loc, filePath string) error { |
9933169c8 localization support |
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
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 |
38 39 40 |
mu.Lock() defer mu.Unlock() |
f84e7607d added dictionary;... |
41 |
d.locales[loc] = l |
a205e8f40 changes |
42 |
d.supported = append(d.supported, loc) |
9933169c8 localization support |
43 44 45 |
return nil } |
f84e7607d added dictionary;... |
46 47 48 |
func (d *Dictionary) Translate(loc, key string) string { return d.locales[loc][key] } |
a205e8f40 changes |
49 50 51 |
func (d *Dictionary) HasLocale(loc string) bool { for _, v := range d.supported { if v == loc { |
f84e7607d added dictionary;... |
52 53 54 55 |
return true } } return false |
9933169c8 localization support |
56 |
} |
a205e8f40 changes |
57 58 59 60 61 62 63 64 65 66 67 68 |
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 } |
3712c373f better localizati... |
69 |
|
5d654d249 interface change |
70 71 |
func (d *Dictionary) GetBestMatchLocale(acceptedLanguages string) (best string) { accepted := d.parseAcceptedLanguageHeader(acceptedLanguages) |
3712c373f better localizati... |
72 73 74 |
best = accepted[0] return } |
5d654d249 interface change |
75 76 |
func (d *Dictionary) parseAcceptedLanguageHeader(acceptedLanguages string) (langs []string) { if acceptedLanguages == "" { |
3712c373f better localizati... |
77 78 79 |
langs = append(langs, d.GetDefaultLocale()) return } |
5d654d249 interface change |
80 |
parts := strings.Split(acceptedLanguages, ",") |
3712c373f better localizati... |
81 82 83 84 85 86 |
for _, p := range parts { langs = append(langs, p) } return } |