localization.go
1.7 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package webutility
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strings"
"sync"
)
type Dictionary struct {
my sync.Mutex
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)
}
mu.Lock()
defer mu.Unlock()
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
}
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
}