-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18n.go
78 lines (66 loc) · 1.48 KB
/
i18n.go
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
package main
import (
"encoding/json"
"log"
"os"
"strings"
"sync"
)
var translationsCache map[string]map[string]string
var cacheMutex sync.RWMutex
func stringInSlice(str string, slice []string) bool {
for _, s := range slice {
if s == str {
return true
}
}
return false
}
func getLanguageCodeFromHeader(acceptLanguageHeader string) string {
defaultCode := "en"
validLanguges := []string{"en", "es", "ca", "de", "fr", "it"}
if acceptLanguageHeader == "" {
return defaultCode
} else {
result := strings.Split(strings.Split(acceptLanguageHeader, ",")[0], "-")[0]
if stringInSlice(result, validLanguges) {
return result
} else {
return defaultCode
}
}
}
func getTranslations(languageCode string) map[string]string {
cacheMutex.RLock()
cachedData, found := translationsCache[languageCode]
cacheMutex.RUnlock()
if found {
return cachedData
}
content, err := os.ReadFile("resources/i18n.json")
if err != nil {
log.Fatal(err)
}
jsonData := string(content)
var data map[string]map[string]string
err = json.Unmarshal([]byte(jsonData), &data)
if err == nil {
rData := make(map[string]string)
for k, v := range data {
value, exists := v[languageCode]
if exists {
rData[k] = value
} else {
rData[k] = v["en"]
}
}
cacheMutex.Lock()
if translationsCache == nil {
translationsCache = make(map[string]map[string]string)
}
translationsCache[languageCode] = rData
cacheMutex.Unlock()
return rData
}
return map[string]string{}
}