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